Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of "finally" in try/catch/finally

The syntax will change from language to language, but this is a general question.

What is the difference between this....

try {      Console.WriteLine("Executing the try statement.");      throw new NullReferenceException(); } catch (NullReferenceException e) {      Console.WriteLine("{0} Caught exception #1.", e); }        finally {      Console.WriteLine("Executing finally block."); } 

and this....

try {     Console.WriteLine("Executing the try statement.");     throw new NullReferenceException(); } catch (NullReferenceException e) {     Console.WriteLine("{0} Caught exception #1.", e); }         Console.WriteLine("Executing finally block."); 

I keep seeing it being used, so I assume there's a good reason to use finally, but I can't figure out how it's any different from just putting code after the statement since it will still run.

Is there ever a scenario where finally doesn't run?

like image 818
Maxx Avatar asked May 23 '13 02:05

Maxx


People also ask

What is the purpose of finally?

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs.

What is the purpose of finally class?

The finally keyword is used to execute code (used with exceptions - try.. catch statements) no matter if there is an exception or not.


2 Answers

In your example, it doesn't make a whole lot of difference.

Picture this, though:

    try     {         Console.WriteLine("Executing the try statement.");         throw new NullReferenceException();     }     catch (SomeOtherException e)     {         Console.WriteLine("{0} Caught exception #1.", e);     }            finally     {         Console.WriteLine("Executing finally block.");     }      Console.WriteLine("Executing stuff after try/catch/finally."); 

In this case, the catch won't catch the error, so anything after the whole try/catch/finally will never be reached. However, the finally block will still run.

like image 136
cHao Avatar answered Oct 07 '22 18:10

cHao


try {     throw new Exception("Error!"); } catch (Exception ex) {     throw new Exception(ex, "Rethrowing!"); } finally {     // Will still run even through the catch kicked us out of the procedure }  Console.WriteLine("Doesn't execute anymore because catch threw exception"); 
like image 32
jdl Avatar answered Oct 07 '22 19:10

jdl