In a Try Catch Finally block, does the finally block always execute no matter what, or only if the catch block does not return an error?
I was under the impression that the finally block only executes if the catch block passes without errors. If the catch block is executed because of an error, shouldn't it stop execution all together and return the error message if any?
The try statement defines the code block to run (to try). The catch statement defines a code block to handle any error. The finally statement defines a code block to run regardless of the result. The throw statement defines a custom error.
No, we cannot write any statements in between try, catch and finally blocks and these blocks form one unit.
The Rule. The finally block on a try / catch / finally will always run — even if you bail early with an exception or a return .
1.4. Please note that only try block is mandatory while catch and finally blocks are optional.
The finally block (nearly) always executes, whether or not there was an exception.
I say nearly because there are a few cases where finally isn't guaranteed to be called:
Furthermore, even if the finally block is entered if a ThreadAbortException
occurs just as the thread enters the finally block the code in the finally block will not be run.
There may be some other cases too...
Not only will a finally block execute following a catch block, try does not even require that any exception be caught for the finally to execute. The following is perfectly legal code:
try
{
//do stuff
}
finally
{
//clean up
}
I actually took out the catch blocks in some code I inherited when the catch block consisted of:
catch(Exception ex)
{
throw ex;
}
In that case, all that was required was to clean up, so I left it with just a try{} and finally{} block and let exceptions bubble up with their stack trace intact.
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