HI WELCOME TO SIRIS

C# finally

Leave a Comment
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

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.