How to Use Multiple Catch Clauses in C#?
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# 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");
}
}
}
}
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.
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# 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.");
}
}
}
Output
Error: 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.