开发者

GOTO statement in C#.NET

try
{...
block:
....
}
catch{ ..}
GOTO block
...
....
finally{...}

Will goto 开发者_运维百科executes in this case??


It won't compile because of 'GOTO block' instead of 'goto block;' and even if it was right it won't compile because C# specifications states (§8.9.3):

The target of a goto identifier statement is the labeled statement with the given label. If a label with the given name does not exist in the current function member, or if the goto statement is not within the scope of the label, a compile-time error occurs. This rule permits the use of a goto statement to transfer control out of a nested scope, but not into a nested scope.

Also I found couple specs interesting for me too:

A goto statement cannot exit a finally block (§8.10). When a goto statement occurs within a finally block, the target of the goto statement must be within the same finally block, or otherwise a compile-time error occurs.

And:

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.

the latter means that if you have

try
{
    ...
    goto Label1;
}
finally
{
    CloseAll();
}

Label1:
   MethodB();

it will call CloseAll() before actually transferring control to the Label1 and executing MethodB().

Makes perfect sense, but I never thought about it...


No. block: label must be outside the try in order for the goto to see it. The code won't even compile. Are you taking a test :)?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜