Part 10 - What happens if finally block throws an exception

This question can also be asked in a slightly different wayHow to handle exceptions that occur in finally block

The exception propagates up, and should be handled at a higher level. If the exception is not handled at the higher level, the application crashes. The "finally" block execution stops at the point where the exception is thrown.

In the example below, notice that the "finally" block in "Hello()" method throws an exception. Hello() method is being called in the Main() method and we don't have any exception handling mechanism in place in the Main() method. So, the application crashes with the exception.

public class Program{public static void Main() { Hello(); }

public static void Hello() {try { // Some code } catch { // Some code }finally {Console.WriteLine("This line will be executed");int result = Convert.ToInt32("TEN");Console.WriteLine("This line will NOT be executed"); } }}

On the other hand, if you include exception handling mechanism(try/catch) in the Main() method, then you will have the opportunity to handle the exception.public static void Main(){try { Hello(); }catch (Exception ex) { // Process and log the exceptionConsole.WriteLine(ex.Message); }}

Irrespective of whether there is an exception or not "finally" block is guaranteed to execute. 1. If the "finally" block is being executed after an exception has occurred in the try block, 2. and if that exception is not handled3. and if the finally block throws an exceptionThen the original exception that occurred in the try block is lost.