No content available!
Yes, the finally block will be executed even after a return statement in a method.
What Is finally? finally defines a block of code we use along with the try keyword. It defines code that's always run after the try and any catch block, before the method is completed. The finally block executes regardless of whether an exception is thrown or caught.
finally block overrides any return values from try and catch blocks.
Yes, finally will be called after the execution of the try or catch code blocks.
Can we have a return statement in the catch or, finally blocks in Java? Can we have a return statement in the catch or, finally blocks in Java? Yes, we can write a return statement of the method in catch and finally block.
Yes, the finally block will be executed even after a return statement in a method. The finally block will always execute even an exception occurred or not in Java. If we call the System.exit () method explicitly in the finally block then only it will not be executed.
Even when we attempt to exit within the try block (via a return statement, a continue statement, a break statement or any exception), the finally block will still be executed. Note that there are some cases in which the finally block will not get executed, such as the following:
We can write "Environment.Exit (0)" inside the "catch" block so that the "finally" block will never get executed.
Yes, the finally
block is executed however the flow leaves the try
block - whether by reaching the end, returning, or throwing an exception.
From the C# 4 spec, section 8.10:
The statements of a finally block are always executed when control leaves a try statement. This is true whether the control transfer occurs as a result of normal execution, as a result of executing a break, continue, goto, or return statement, or as a result of propagating an exception out of the try statement.
(Section 8.10 has a lot more detail on this, of course.)
Note that the return value is determined before the finally block is executed though, so if you did this:
int Test()
{
int result = 4;
try
{
return result;
}
finally
{
// Attempt to subvert the result
result = 1;
}
}
... the value 4 will still be returned, not 1 - the assignment in the finally
block will have no effect.
A finally block will always be executed and this will happen before returning from the method, so you can safely write code like this:
try {
return "foo";
} finally {
// This will always be invoked
}
or if you are working with disposable resources:
using (var foo = GetFoo())
{
// foo is guaranteed to be disposed even if an exception is thrown
return foo.Bar();
}
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