最后尝试捕获:如果没有抛出异常,请执行一些操作

low*_*key 24 c# try-catch

我想知道,如果没有抛出异常,有没有办法只执行一个块?

我能想到的最好的是:

bool exception = false;
try{
    // something
}catch(Exception e){
    exception = true;
}finally{
    if(!exception){
        // i can do what i want here
    } 
}
Run Code Online (Sandbox Code Playgroud)

有没有更好的办法?

Jon*_*Jon 46

当然有:把它放在try块的底部.

try{
    // something
    // i can do what i want here
}catch(Exception e){
    // handle exception
}
Run Code Online (Sandbox Code Playgroud)

这并不完全等同于您的原始代码,如果"您想要的东西"抛出,异常将在本地捕获(这不会发生在原始方案中).这是您可能或可能不关心的事情,并且很有可能不同的行为也是正确的行为.

如果你想恢复旧的行为,你也可以使用这个finally不仅仅是为了编写"if no exceptions"条件的变体:

var checkpointReached = false;
try{
    // something
    checkpointReached = true;
    // i can do what i want here
}catch(Exception e){
    if (checkpointReached) throw; // don't handle exceptions after the checkpoint
    // handle exception
}
Run Code Online (Sandbox Code Playgroud)


Den*_*ret 6

您不需要 finally 子句。

一个办法 :

bool exception = false;
try{
    // something
}catch(Exception e){
    exception = true;
}
if(!exception){
     // u can do what u want here
} 
Run Code Online (Sandbox Code Playgroud)

通常,您只需在 catch 子句中返回一个 return ,这样您甚至不必测试:

try{
    // something
}catch(Exception e){
   // do things
   return;
}
// u can do what u want here
Run Code Online (Sandbox Code Playgroud)

或(取决于用例并且通常不太清楚,特别是如果您有多个预期的异常-您不想进行 try-catch 嵌套...):

try{
    // something
    // u can do what u want here
}catch(Exception e){
   // do things
}
Run Code Online (Sandbox Code Playgroud)


Jef*_*ter 5

你可以构造你的代码,它doSomething是块中的最后一个语句,它不会抛出?

bool exception = false;
try{
  // something
  doSomething();
} catch {
}
finally {
}
Run Code Online (Sandbox Code Playgroud)