最后尝试 catch:如果没有引发异常,请执行某些操作
本文关键字:执行 操作 异常 catch 如果没有 最后 | 更新日期: 2023-09-27 18:33:07
我想知道,有没有办法只在没有抛出异常的情况下执行一个块?
我能想到的最好的是:
bool exception = false;
try{
// something
}catch(Exception e){
exception = true;
}finally{
if(!exception){
// i can do what i want here
}
}
有没有更好的方法?
当然有:把它放在try
块的底部。
try{
// something
// i can do what i want here
}catch(Exception e){
// handle exception
}
这并不完全等同于您的原始代码,因为如果抛出"您想要的",异常将被本地捕获(这不会发生在您的原始方案中)。这是你可能关心也可能不关心的事情,而且很有可能不同的行为也是正确的。
如果你想恢复旧的行为,你也可以使用这个不需要finally
的变体,只是为了编写"如果没有例外"条件:
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
}
你不需要 finally 子句。
一个解决方案:
bool exception = false;
try{
// something
}catch(Exception e){
exception = true;
}
if(!exception){
// u can do what u want here
}
通常,您只需在 catch 条款中返回,这样您甚至不必测试:
try{
// something
}catch(Exception e){
// do things
return;
}
// u can do what u want here
或者(取决于用例并且通常不太清楚,特别是如果您预期有多个异常 - 您不希望有 try-catch 嵌套......
try{
// something
// u can do what u want here
}catch(Exception e){
// do things
}
你能构建你的代码,让doSomething
是块中的最后一个语句并且它不会抛出吗?
bool exception = false;
try{
// something
doSomething();
} catch {
}
finally {
}
是的,有:把它放在 try 块的末尾:)
不 - 你所拥有的可能是在 C# 中做到这一点的最佳方式。
这是假设:
- 您不希望"我可以在这里做我想做的事"代码在
try
块的底部运行。(也许是因为您不希望该代码中的异常由主catch
块处理。 - 您不希望"我可以在这里做我想做的事"代码完全在
try...catch...finally
结构之外运行。(也许是因为您希望该代码在位于finally
块内的其他代码之前运行。
虽然你的代码没有错,但这是不必要的。只需将要执行的代码放在 try 块的底部:
try {
...
// No errors to this point, run what you wanted to run in the finally.
}
catch(Exception e) {
...
}
我相信
你正在寻找尝试:
try{
// something
try{
// something else not interfering with first try
} catch(Exception innerEx){
// something else threw this innerEx
}
}catch(Exception outerEx){
// something threw this outerEx
}
虽然这通常被认为是不好的做法,但我更喜欢它而不是标志版本。