gpt4 book ai didi

c# - 最后 try catch : Do something if no exception is thrown

转载 作者:IT王子 更新时间:2023-10-29 04:23:04 26 4
gpt4 key购买 nike

我想知道,有没有办法只在没有抛出异常的情况下执行一个 block ?

我能想到的最好的是:

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

有没有更好的办法?

最佳答案

当然有:把它放在 try block 的底部。

try{
// something
// i can do what i want here
}catch(Exception e){
// handle exception
}

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

如果你想恢复旧的行为,你也可以使用这个不需要 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
}

关于c# - 最后 try catch : Do something if no exception is thrown,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10431413/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com