How to Use Multiple Catch Clauses in C#?
Last Updated :
11 Jul, 2025
In C#, the main purpose of a catch block is to handle exceptions raised in the try block. A catch block is executed only when an exception occurs in the program. We can use multiple catch blocks with a single try block to handle different types of exceptions. Each catch block is designed to handle a specific type of exception.
Note: C# does not allow multiple catch blocks for the same exception type, because it will cause a compile-time error. The catch blocks are evaluated in the order they appear. If an exception matches the first catch block, the remaining catch blocks are ignored.
Syntax of try-catch with Multiple Catch Clauses:
try
{ // Code that may throw an exception }
catch (ExceptionType1 ex)
{ // Handle ExceptionType1 }
catch (ExceptionType2 ex)
{ // Handle ExceptionType2 }
// Add more catch blocks as needed
finally
{ // Code that executes regardless of exceptions (optional) }
Example 1: Handling DivideByZeroException and IndexOutOfRangeException
In this example, the try block generates two types of exceptions:
- DivideByZeroException: When trying to divide a number by zero.
- IndexOutOfRangeException: When accessing an array with an invalid index.
Each exception is handled by a specific catch block.
C#
// C# program to illustrate multiple catch blocks
using System;
class Geeks
{
static void Main()
{
// Arrays for demonstration
int[] num = { 8, 17,5 };
int[] divisors = { 2, 0, 4 };
// Iterate through numbers and divisors
for (int i = 0; i < num.Length; i++)
{
try
{
// Display current number and divisor
Console.WriteLine($"Number: {num[i]}");
Console.WriteLine($"Divisor: {divisors[i]}");
// Perform division
Console.WriteLine($"Quotient: {num[i] / divisors[i]}");
}
catch (DivideByZeroException)
{
// Handle division by zero
Console.WriteLine("Error: Division by zero is not allowed.");
}
catch (IndexOutOfRangeException)
{
// Handle invalid array index
Console.WriteLine("Error: Index is out of range.");
}
finally
{
// Execute cleanup code (if needed)
Console.WriteLine("Operation completed.\n");
}
}
}
}
OutputNumber: 8
Divisor: 2
Quotient: 4
Operation completed.
Number: 17
Divisor: 0
Error: Division by zero is not allowed.
Operation completed.
Number: 5
Divisor: 4
Quotient: 1
Operation completed.
Example 2: Handling Multiple Exception Types in Parsing
This example demonstrates using multiple catch blocks to handle exceptions such as FormatException (invalid input format) and OverflowException (data out of range).
C#
// C# program to demonstrate multiple catch clauses
using System;
class Geeks
{
static void Main()
{
try
{
// Trying to parse invalid input
byte data = byte.Parse("a");
Console.WriteLine($"Parsed Data: {data}");
}
catch (FormatException)
{
// Handle invalid input format
Console.WriteLine("Error: The entered value is not a valid number.");
}
catch (OverflowException)
{
// Handle data out of range for a byte
Console.WriteLine
("Error: The entered value is outside the valid range for a byte.");
}
catch (Exception ex)
{
// General exception handling (fallback)
Console.WriteLine($"Unexpected error: {ex.Message}");
}
finally
{
// Execute code regardless of exceptions
Console.WriteLine("Operation completed.");
}
}
}
OutputError: The entered value is not a valid number.
Operation completed.
Important Points:
- The catch blocks are evaluated in the order they appear. Ensure more specific exceptions (e.g., DivideByZeroException) appear before more general ones (e.g., Exception).
- Use a finally block for cleanup operations like closing resources, which should run regardless of whether an exception is raised.
- Always use a general catch (Exception ex) block at the end to handle any unexpected exceptions.
Similar Reads
Null-Coalescing Operator in C# In C#, ?? operator is known as Null-coalescing operator. It will return the value of its left-hand operand if it is not null. If it is null, then it will evaluate the right-hand operand and returns its result. Or if the left-hand operand evaluates to non-null, then it does not evaluate its right-han
4 min read
List.FindIndex() Method in C# with Examples List<T>.FindIndex Method is used to search for an element that matches the conditions defined by a specified predicate and returns the index of the first occurrence within the List<T>. If an item that matches the conditions is not found then this method will return -1. There are 3 method
6 min read
C# Program to Demonstrate the Use of FailFast() Method of Environment Class Environment Class provides information about the current platform and manipulates, the current platform. It is useful for getting and setting various operating system-related information. We can use it in such a way that retrieves command-line arguments information, exit codes information, environme
3 min read
Console.OpenStandardError Method in C# This method is used to acquire a standard error stream. This method can be used to reacquire the standard error stream after it has been changed by the SetError method. Syntax: public static System.IO.Stream OpenStandardError (); Returns: This method returns the standard error stream. Example: The b
2 min read
C# - Nesting of Try and Catch Blocks In C#, the nesting of the try-and-catch block is allowed. The nesting of a try block means one try block can be nested into another try block. The various programmer uses the outer try block to handle serious exceptions, whereas the inner block for handling normal exceptions.Example 1: Handling Divi
3 min read
C# System Level Exception vs Application Level Exception In C#, exceptions are categorized into two main types based on their origin and usage, which are System-level exceptions and Application-level exceptions. Understanding the difference between these two helps in managing exceptions properly and choosing the right exception-handling approach.System Le
3 min read