C# 中的 CATCH 块中的 GOTO 最终执行了吗?
Does GOTO in CATCH block in c# execute FINALLY?
很简单的问题:
int retryAttempts = 3;
retry:
try {
await getSemaphore();
throw new Exception();
}
catch {
if (0 > retryAttempts--) {
await Task.Delay(5000);
goto retry;
}
return;
}
finally {
releaseSemaphore();
}
在这个例子中,信号量会被释放一到三次吗?
finally
将在您每次离开 catch 块时执行。所以在你的情况下 releaseSemaphore()
将被调用三次(在每个 goto
之后)。
我也邀请你阅读关于try-finallyhere
的官方文档
C# 规范 (ECMA-334) states as follows:
A goto statement is executed as follows:
If the goto
statement exits one or more try
blocks with associated finally
blocks, control is initially transferred to the finally
block of the innermost try
statement. When and if control reaches the end point of a finally
block, control is transferred to the finally
block of the next enclosing try
statement. This process is repeated until the finally
blocks of all intervening try
statements have been executed.
Control is transferred to the target of the goto
statement.
因此 goto
仅在所有相关 finally
块执行后发生。
很简单的问题:
int retryAttempts = 3;
retry:
try {
await getSemaphore();
throw new Exception();
}
catch {
if (0 > retryAttempts--) {
await Task.Delay(5000);
goto retry;
}
return;
}
finally {
releaseSemaphore();
}
在这个例子中,信号量会被释放一到三次吗?
finally
将在您每次离开 catch 块时执行。所以在你的情况下 releaseSemaphore()
将被调用三次(在每个 goto
之后)。
我也邀请你阅读关于try-finallyhere
的官方文档C# 规范 (ECMA-334) states as follows:
A goto statement is executed as follows:
If the
goto
statement exits one or moretry
blocks with associatedfinally
blocks, control is initially transferred to thefinally
block of the innermosttry
statement. When and if control reaches the end point of afinally
block, control is transferred to thefinally
block of the next enclosingtry
statement. This process is repeated until thefinally
blocks of all interveningtry
statements have been executed.Control is transferred to the target of the
goto
statement.
因此 goto
仅在所有相关 finally
块执行后发生。