.Net Framework
C# Tutorial
C# Control Statement
C# Arrays
C# Object Class
C# Properties
C# Inheritance
C# Polymorphism
C# Abstraction
C# Strings
C# Exception Handling
C# File IO
C# Collections
C# Generics
C# Delegates
C# Reflection
Anonymous Function
C# Multithreading
C# Synchronization
C# Web Service
C# Misc
C# New Features
C# Programs
C# Interview Questions
ADO.NET Tutorial
ASP.NET Tutorial
C# finally
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
using System;
public class ExExample
{
public static void Main(string[] args)
{
try
{
int a = 10;
int b = 0;
int x = a / b;
}
catch (Exception e) { Console.WriteLine(e); }
finally { Console.WriteLine("Finally block is executed"); }
Console.WriteLine("Rest of the code");
}
}
public class ExExample
{
public static void Main(string[] args)
{
try
{
int a = 10;
int b = 0;
int x = a / b;
}
catch (Exception e) { Console.WriteLine(e); }
finally { Console.WriteLine("Finally block is executed"); }
Console.WriteLine("Rest of the code");
}
}
Output:
System.DivideByZeroException: Attempted to divide by zero.
Finally block is executed
Rest of the code
Finally block is executed
Rest of the code
C# finally example if exception is not handled
using System;
public class ExExample
{
public static void Main(string[] args)
{
try
{
int a = 10;
int b = 0;
int x = a / b;
}
catch (NullReferenceException e) { Console.WriteLine(e); }
finally { Console.WriteLine("Finally block is executed"); }
Console.WriteLine("Rest of the code");
}
}
public class ExExample
{
public static void Main(string[] args)
{
try
{
int a = 10;
int b = 0;
int x = a / b;
}
catch (NullReferenceException e) { Console.WriteLine(e); }
finally { Console.WriteLine("Finally block is executed"); }
Console.WriteLine("Rest of the code");
}
}
Output:
Unhandled Exception: System.DivideBy