VOOZH about

URL: https://www.geeksforgeeks.org/c-sharp/c-sharp-how-to-use-multiple-catch-clause/

⇱ How to Use Multiple Catch Clauses in C#? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Use Multiple Catch Clauses in C#?

Last Updated : 20 Apr, 2026

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.


Output
Number: 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.


Explanation: Since both operands are integers, C# performs integer division, which truncates the decimal part. Therefore, 5 / 4 results in 1 instead of 1.25.

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).


Output
Number is out of range.

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.
Comment
Article Tags:

Explore