In the C# finally block is used, you can clean up any resources that are allocated in a try block, and you can run code even if an exception occurs in.
Syntax
try
{
//put suspected c# code here. When an exception occurs, the control will move to the catch block
}
catch
{
//Catch the exception
}
finally
{
// clean up resources
}
C# try-catch-finally Example
using System;
public class ExExample
{
public static void Main(string[] args)
{
try
{
int firstNumber = 10;
int secondNumber = 0;
int result = firstNumber / secondNumber; }
catch (Exception e) { Console.WriteLine(e); }
finally { Console.WriteLine("Finally block is executed"); }
Console.WriteLine("Reset c# code here");
}
}
Output
System.DivideByZeroException: Attempted to divide by zero.
at ExExample.Main(String[] args) in d:\Windows\Temp\fxh13qx1.0.cs:line 11
Finally block is executed
Rest c# code here
C# finally example if exception is not handled
using System;
public class ExExample
{
public static void Main(string[] args)
{
try
{
int firstNumber = 10;
int secondNumber = 0;
int result = firstNumber / secondNumber;
}
catch (NullReferenceException e) { Console.WriteLine(e); }
finally { Console.WriteLine("Finally block is executed"); }
Console.WriteLine("Rest of the code");
}
}
Output
Finally block is executed
Run-time exception (line 11): Attempted to divide by zero.
Stack Trace:
[System.DivideByZeroException: Attempted to divide by zero.]
at ExExample.Main(String[] args) :line 11