C Sharp finally

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

C# finally

C# finally block is used to execute important code which is to be executed whether exception is handled or not. It must be preceded by catch or try block.

C# finally example if exception is handled

 
  1. using System;  
  2. public class ExExample  
  3. {  
  4.     public static void Main(string[] args)  
  5.     {  
  6.         try  
  7.         {  
  8.             int a = 10;  
  9.             int b = 0;  
  10.             int x = a / b;  
  11.         }  
  12.         catch (Exception e) { Console.WriteLine(e); }  
  13.         finally { Console.WriteLine("Finally block is executed"); }  
  14.         Console.WriteLine("Rest of the code");  
  15.     }  
  16. }  

Output:

System.DivideByZeroException: Attempted to divide by zero.
Finally block is executed
Rest of the code

C# finally example if exception is not handled

 
  1. using System;  
  2. public class ExExample  
  3. {  
  4.     public static void Main(string[] args)  
  5.     {  
  6.         try  
  7.         {  
  8.             int a = 10;  
  9.             int b = 0;  
  10.             int x = a / b;  
  11.         }  
  12.         catch (NullReferenceException e) { Console.WriteLine(e); }  
  13.         finally { Console.WriteLine("Finally block is executed"); }  
  14.         Console.WriteLine("Rest of the code");  
  15.     }  
  16. }  

Output:

Unhandled Exception: System.DivideBy