If you run the code below it actually executes the finally after every call to the goto:
int i = 0;
Found:
i++;
try
{
throw new Exception();
}
catch (Exception)
{
goto Found;
}
finally
{
Console.Write("{0}\t", i);
}
Why?
The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs.
It defines a block of code to run when the try... except...else block is final. The finally block will be executed no matter if the try block raises an error or not. This can be useful to close objects and clean up resources.
A finally block always executes, regardless of whether an exception is thrown.
We generally use the finally block to execute clean up code like closing connections, closing files, or freeing up threads, as it executes regardless of an exception.
The following text comes from the C# Language Specification (8.9.3 The goto statement)
A goto statement is executed as follows:
Why do you expect it to not execute?
If you have try/catch/finally or try/finally block, finally block executes no matter what code you may have in the try or catch block most of the time.
Instead of goto, consider 'return'.
//imagine this try/catch/finally block is inside a function with return type of bool.
try
{
throw new Exception();
}
catch (Exception)
{
return false; //Let's say you put a return here, finally block still executes.
}
finally
{
Console.WriteLine("I am in finally!");
}
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