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
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.
The code inside the finally block gets always executed, regadless if there was an exception. By the way, I think there are already numerous threads on SO that deal with this question.
the finally block executes in almost every case. That's why it's called 'finally'.
For an example, see this article on c-sharpcorner.com.
Update: It's true, if you plug the cable, melt the processor or grind the motherboard, even the most final 'finally' will not be executed.
But in almost every 'normal' scenario, i.e. wether your code throws an exception or not, the finally block will be executed. To my knowledge the only 'real' exception to this rule is a stackoverflow exception which will terminate the program w/o entering finally.
Update 2: This question was asked specifically for C#. This answer is NOT covering Java, Python, Matlab or Scheme.
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...
The finally block will execute, but you'll need to be careful of exceptions within the finally block.
try {
// some disposable method "o"
} finally {
o.Dispose(); // if o is null, exception is thrown
// anything after this exception will fail to execute
}