Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try catch finally question

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?

like image 564
Scott W Avatar asked Jul 21 '10 22:07

Scott W


People also ask

How do you use Finally in try catch?

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.

Can we use try catch in finally block?

No, we cannot write any statements in between try, catch and finally blocks and these blocks form one unit.

Does finally run after try catch?

The Rule. The finally block on a try / catch / finally will always run — even if you bail early with an exception or a return .

Is finally mandatory in try catch?

1.4. Please note that only try block is mandatory while catch and finally blocks are optional.


2 Answers

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:

  • If there is an infinite loop or deadlock in your code so that the execution remains inside the try or catch blocks then the finally block will never execute.
  • If your application is terminated abruptly by killing the process.
  • Power cut.
  • Calling Environment.FailFast.
  • Some exceptions such as:
    • StackOverflowException
    • OutOfMemoryException
    • ExecutingEngineException (now obsolete)
  • An exception thrown in a finalizer (source).

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...

like image 59
Mark Byers Avatar answered Sep 20 '22 17:09

Mark Byers


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.

like image 42
Michael Blackburn Avatar answered Sep 20 '22 17:09

Michael Blackburn