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?
The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs.
The finally keyword is used to execute code (used with exceptions - try.. catch statements) no matter if there is an exception or not.
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.
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");
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