try
{...
block:
....
}
catch{ ..}
GOTO block
...
....
finally{...}
Will goto executes in this case??
The use of goto statement may lead to code that is buggy and hard to follow. For example, one: for (i = 0; i < number; ++i) { test += i; goto two; } two: if (test > 5) { goto three; } ... .. ... Also, the goto statement allows you to do bad stuff such as jump out of the scope.
The goto statement can be used to alter the flow of control in a program. Although the goto statement can be used to create loops with finite repetition times, use of other loop structures such as for, while, and do while is recommended. The use of the goto statement requires a label to be defined in the program.
NOTE − Use of goto statement is highly discouraged in any programming language because it makes difficult to trace the control flow of a program, making the program hard to understand and hard to modify.
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 afinally
block, the target of the goto statement must be within the samefinally
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 :)?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With