如果在Try/Catch中没有捕获,则运行代码

3D-*_*tiv 7 c#

当我使用Try/Catch时,如果没有检测到错误且没有Catch,有没有像If/Else那样运行代码的方法?

try
{
    //Code to check
}
catch(Exception ex)
{
    //Code here if an error
}

//Code that I want to run if it's all OK ?? 

finally
{
    //Code that runs always
}
Run Code Online (Sandbox Code Playgroud)

Joe*_*oey 23

try块的末尾添加代码.显然,如果之前没有例外,你将只能到达那里:

try {
  // code to check

  // code that you want to run if it's all ok
} catch {
  // error
} finally {
  // cleanup
}
Run Code Online (Sandbox Code Playgroud)

你可能应该改变你的捕获方式,你只捕获你期望的异常,而不是弄平一切,这可能包括你想要运行的代码中抛出的异常,如果一切正常«.

  • 我认为这不是一个很好的解决方案,特别是对于内置错误类型。正如您所说“您只会捕获您期望的异常”。因此,如果我期望“FooException”来自“//要检查的代码”,那么我只将该代码包含在“try”块中。我不希望从“//如果一切正常就运行的代码”中出现“FooException”,但您的解决方案仍然会错误地捕获它。对于通用错误类型来说,这尤其是一个问题。但是,如果所有函数都有自己独特的错误类型,那么您的解决方案将是完美的。 (3认同)

Pol*_*ial 11

如果您需要它在try代码成功时始终执行,请将其放在try块的末尾.只要try块中的前一个代码在没有异常的情况下运行,它就会运行.

try
{
    // normal code

    // code to run if try stuff succeeds
}
catch (...)
{
    // handler code
}
finally
{
    // finally code
}
Run Code Online (Sandbox Code Playgroud)

如果您需要替代异常处理"成功"代码,您可以始终嵌套您的try/catches:

try
{
    // normal code

    try
    {
        // code to run if try stuff succeeds
    }
    catch (...)
    {
        // catch for the "succeded" code.
    }
}
catch (...)
{
    // handler code
    // exceptions from inner handler don't trigger this
}
finally
{
    // finally code
}
Run Code Online (Sandbox Code Playgroud)

如果您的"成功"代码必须在finally之后执行,请使用变量:

bool caught = false;
try
{
    // ...
}
catch (...)
{
    caught = true;
}
finally
{
    // ...
}

if(!caught)
{
    // code to run if not caught
}
Run Code Online (Sandbox Code Playgroud)


Ode*_*ded 5

只需将它放在可能引发异常的代码之后.

如果抛出异常,它将不会运行,如果没有抛出异常,它将运行.

try
{
    // Code to check
    // Code that I want to run if it's all OK ??  <-- here
}
catch(Exception ex)
{
    // Code here if an error
}
finally
{
    // Code that runs always
}
Run Code Online (Sandbox Code Playgroud)