Open In App

Exception Handling in C#

Last Updated : 20 Sep, 2025
Comments
Improve
Suggest changes
21 Likes
Like
Report

In C#, exception handling is the process of responding to runtime anomalies, called exceptions, in a controlled way. Proper handling ensures that a program continues to run or exits gracefully instead of crashing unexpectedly.

C# provides structured exception handling using the keywords try, catch, finally, and throw.

Syntax:

try{

// Code that may throw an exception

}

catch (ExceptionType ex){

// Code to handle the exception

}

finally{

// Code that will always execute

}

Keywords for Exception Handling

1. try

The try block contains the code that might throw an exception. Only the code inside the try block is monitored for exceptions.

C#
using System; class Program {  static void Main()  {  try  {  int result = 10 / 0; // Risky operation  Console.WriteLine(result);  }  catch (DivideByZeroException ex)  {  Console.WriteLine("Division by zero detected.");  }  } } 

Explanation:

  • The division operation is placed inside try because it may cause DivideByZeroException.
  • Only code in try is monitored for exceptions.

2. catch

The catch block handles exceptions thrown in the try block. You can have multiple catch blocks to handle different exception types.

C#
try {  int[] arr = { 1, 2, 3 };  Console.WriteLine(arr[5]); // IndexOutOfRangeException } catch (IndexOutOfRangeException ex) {  Console.WriteLine("Array index is out of range."); } catch (Exception ex) {  Console.WriteLine("Some other exception occurred."); } 

Explanation:

  • The first matching catch block handles the exception.
  • The second catch (Exception) acts as a fallback for any other exceptions.

3. finally

The finally block always executes, whether an exception occurs or not. It is mainly used for cleanup tasks like closing files, releasing resources, or clearing memory.

C#
try {  int result = 10 / 2;  Console.WriteLine(result); } catch (DivideByZeroException) {  Console.WriteLine("Division by zero."); } finally {  Console.WriteLine("This always executes."); } 

Explanation:

  • Even if no exception occurs, the code in finally runs.
  • Ensures essential cleanup operations are performed.

4. throw

The throw keyword is used to manually raise an exception. It can be used to signal that an error or invalid condition has occurred.

C#
int age = 15; if (age < 18) {  throw new ArgumentException("Age must be 18 or older."); } 

Explanation:

  • throw creates an exception object and passes it up the call stack.
  • The exception can be caught by a try-catch block in the calling code.

Example: Handling Division by Zero

C#
using System; class Program {  static void Main()  {  int a = 10, b = 0;  try  {  int result = a / b; // May throw DivideByZeroException  Console.WriteLine(result);  }  catch (DivideByZeroException ex)  {  Console.WriteLine("Error: Division by zero is not allowed.");  }  finally  {  Console.WriteLine("Execution of try-catch block finished.");  }  } } 

Output:

Error: Division by zero is not allowed.

Execution of try-catch block finished.

Explanation:

  • The try block contains the risky code.
  • The catch block handles the specific exception.
  • The finally block executes irrespective of an exception, ensuring cleanup or final actions.

Multiple Catch Blocks

C# allows multiple catch blocks to handle different types of exceptions:

C#
try {  int[] arr = { 1, 2, 3 };  Console.WriteLine(arr[5]); // Throws IndexOutOfRangeException } catch (DivideByZeroException) {  Console.WriteLine("Division by zero error."); } catch (IndexOutOfRangeException) {  Console.WriteLine("Array index is out of range."); } catch (Exception) {  Console.WriteLine("Some other exception occurred."); } 

Output:

Array index is out of range.

Key Points

  • Exception handling prevents programs from crashing due to runtime errors.
  • Use specific exceptions in catch blocks for more precise error handling.
  • The finally block is optional but useful for cleanup.
  • Use throw to raise exceptions intentionally for invalid conditions.

Explore