C# | finally keyword

In programming, sometimes an exception may cause an error which ends the current method. However, that method might have opened a file or a network that needs to be closed. So, to overcome such types of problem, C# provides a special keyword named as finally keyword. It is a reserved keyword in C#.
The finally block will execute when the try/catch block leaves the execution, no matter what condition cause it. It always executes whether the try block terminates normally or terminates due to an exception. The main purpose of finally block is to release the system resources. The finally block follows try/catch block.

Syntax:

try {

    // code...
}

// this is optional
catch {

   // code..
}

finally
{
    // code..
}

Important Points:

  • In C#, multiple finally blocks in the same program are not allowed.
  • The finally block does not contain any return, continue, break statements because it does not allow controls to leave the finally block.
  • You can also use finally block only with a try block means without a catch block but in this situation, no exceptions are handled.
  • The finally block will be executed after the try and catch blocks, but before control transfers back to its origin.

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to demonstrate finally
using System;
  
class Geek {
      
    // A method that throws an
    // exception and has finally. 
    // This method will be called
    // inside try-catch. 
    static void A() 
    
        try {
              
            Console.WriteLine("Inside A"); 
            throw new Exception("Throwing Exception");
        
          
        finally
        
            Console.WriteLine("A's finally"); 
        
    
  
    // This method also calls
    // finally. This method 
    // will be called outside
    // try-catch. 
    static void B() 
    
          
        try
              
            Console.WriteLine("Inside B"); 
            return
        
          
        finally
        
            Console.WriteLine("B's finally"); 
        
    
  
// Main Method
public static void Main(String[] args) 
    try
          
        A(); 
    
      
    catch (Exception) { 
          
        Console.WriteLine("Exception Caught"); 
    
    B(); 

chevron_right


Output:

Inside A
A's finally
Exception Caught
Inside B
B's finally

Example 2: Using finally block with Handled Exception

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to illustrate the finally
// block with handled exception
using System;
  
public class GFG {
  
    // Main Method
    static public void Main()
    {
  
        // variables
        int number = 4;
        int divisor = 0;
  
        // try block
        // This block raise exception
        try {
  
            int output = number / divisor;
        }
  
        // catch block
        // This block handle exception
        catch (DivideByZeroException) {
  
            Console.WriteLine("Not possible to divide by zero!");
        }
  
        // finally block
        // This block release the 
        // resources of the system
        // and this block always executes
        finally {
  
            Console.WriteLine("Finally Block!");
        }
    }
}

chevron_right


Output:

Not possible to divide by zero!
Finally Block!

Explanation: In the above example, an exception(DivideByZeroException) is generated within the try block that is caught by the catch block associated with the try block. Now after try-catch blocks leave their execution finally block executes and release the resources of the system that are used by the try-catch block.

Example 3:Using finally block with Unhandled Exception

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program illustrate the finally
// block with unhandled exception
using System;
   
public class GFG {
      
    // Main method
    static public void Main () {
          
    // variables
    int number = 4;
    int divisor = 0;
    int output;    
       
    // In this block exception raise
    // Here this exception in unhandled
    // due to the absence of catch block
    try
    {
         output = number/divisor;      
    }
       
    // finally block, this block always
    // executes 
    finally
    {
        Console.WriteLine("Finally Block!");
    }
    }
}

chevron_right


Output:

Finally Block!

Runtime Errors:

Unhandled Exception:
System.DivideByZeroException: Attempted to divide by zero.
at GFG.Main () in :0
[ERROR] FATAL UNHANDLED EXCEPTION: System.DivideByZeroException: Attempted to divide by zero.
at GFG.Main () in :0

Explanation: In this example, an exception(DivideByZeroException) is generated within the try block but does not handle because catch block associated to the try block is not present. In this situation when the try block leaves its execution, then finally block executes and release the resources of the system. It means finally block does not care whether the exception is handled or not.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.