gpt4 book ai didi

c# - 跳出 finally block

转载 作者:太空宇宙 更新时间:2023-11-03 17:12:04 25 4
gpt4 key购买 nike

我正在寻找关键字或干净的方式来不使用选择语句退出finally block 。考虑以下示例:

private bool AtteptToDoSomething()
{
try
{
MethodThatCouldFail();
return true;
}
catch
{
return false;
}
finally
{
//Jump out of function here?

//... to avoid executing this under certain conditions
DoSomethingFinalizing();
}
}

失败的尝试:

finally
{
return;
break;
continue;
goto ExitSymbol;
//This works, but would require a second try-catch block
throw new Exception();
}

上述示例的编译器错误包括:

Control cannot leave the body of a finally clause

Cannot jump out of the finally block

现在很清楚,finally block 不能通过任何常规 方式转移控制。

a pretty good explanation why this won't work with continue ,但不幸的是,这不是为什么在任何其他情况下都不能这样做。

是否有任何(基于 CLR 或 C# 的)不允许/不可能这样做的原因?

除 throw 外,此限制是否有任何异常(exception)情况?

最佳答案

你不能。

这是设计使然,并在 C# 规范中进行了描述:8.10 The try statement.

It is a compile-time error for a break, continue, or goto statement to transfer control out of a finally block. When a break, continue, or goto statement occurs in a finally block, the target of the statement must be within the same finally block, or otherwise a compile-time error occurs.

It is a compile-time error for a return statement to occur in a finally block.

要制作你想要的东西,你可以这样做:

try {}
catch {}
finally
{
Magic();
}

然后

  void Magic()
{
if (x == y)
return;
else
a = b;
}

关于c# - 跳出 finally block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36622877/

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