How To Use Multiple Catch Clauses In C#

In this guide, we will explore the utilization of multiple catch blocks in a C# program, accompanied by illustrative examples. Prior to delving into the application of multiple catch blocks, it is essential to comprehend the purpose and functionality of a catch block.

What is a Catch Block?

Each catch block functions as a dedicated exception handler, specifically designed to manage a particular type of Exception indicated by its parameters. An exception handler can be designated to handle a specific type of exception by specifying the Type parameter, which should correspond to the name of a class inheriting from the Throwable class. Handlers are able to reference exceptions by their designated names. When a catch block is triggered, it represents a section of code that is executed in response to the exception handler being invoked. The runtime system triggers an exception handler when it is the initial exception handler in the call stack whose ExceptionType matches the type of exception that has been thrown. In such scenarios, the system validates the association between the thrower object and the exception handler argument.

In C#, we have the ability to incorporate multiple Catch blocks within Try blocks. Employing multiple catch blocks is a common practice for managing various types of exceptions. Attempting to use multiple catch blocks for a single exception type in C# will lead to a compile-time error as the language does not support this feature. Following a catch block, there is always a try block. Typically, catch blocks are evaluated based on their sequence within the code. When an exception type aligns with the first catch block, the execution proceeds with the first catch block while disregarding the subsequent ones. If the initial catch block fails to match the exception type, the compiler moves on to the next catch block.

Syntax:

It has the following syntax:

Example

try {

//  executable code

}

// The first catch block
catch(Exception_type) {

// statements

}

//The second catch block
catch(Exception_type) {

//  statements

}

Examples:

Here are a few illustrations to enhance comprehension of how catch blocks are utilized in C#.

The provided example demonstrates the generation of two distinct exceptions: DivideByZeroException and IndexOutOfRangeException. To manage these exceptions effectively, we will employ two Catch blocks that are linked to a single Try block.

The catch block was designed to handle various exception types. Catch block 1 is used to capture DivideByZeroException, while catch block 2 is employed to manage IndexOutOfRangeException.

Filename: Catch.cs

Example

// A C# Program to implement the use of multi-catch block
using System; 

class Catch{ 

	// Main Method 
	static void Main() 
	{ 

		// the value of the numbers is greater than its divisors
		int[] numbers = { 18, 19, 28, 35, 56 }; 
		int[] divisors = { 9, 0, 1, 0 }; 
		for (int j = 0; j < numbers.Length; j++) 
			//It raises two different types of exceptions 
			try { 
				Console.WriteLine("The Number: " + 
                                                  numbers[j]); 
				Console.WriteLine("The Divisor value: " + divisors[j]); 
				Console.WriteLine("The Quotient is: " + numbers[j] / 
                                           divisors[j]); 
			} 
			// The first catch block is utilized for handling the
			// handling DivideByZeroException 
			catch (DivideByZeroException) { 

				Console.WriteLine("Division by zero is impossible."); 
			} 
			//The second catch block is utilized for handling the
			// handling IndexOutOfRangeException 
			catch (IndexOutOfRangeException) { 
				Console.WriteLine("The Index value is Out of Range"); 
			} 
	} 
}

Output:

Output

The Number: 18
The Divisor value: 9
The Quotient is: 2
The Number: 19
The Divisor value: 0
Division by zero is impossible.
The Number: 28
The Divisor value: 1
The Quotient is: 28
The Number: 35
The Divisor value: 0
Division by zero is impossible.
The Number: 56
The Index value is Out of Range

Explanation:

Array creation: In this instance, two arrays (numbers and divisors) are set up with integer values.

The software utilizes a for loop to iterate through the items in an array, a try block, and the expression numbers[j] / divisors(j) (this statement is executed within the loop).

The Try block is succeeded by two catch blocks. Each Catch block is designated to handle specific exceptions that may occur during the execution of the code within the Try block.

The catch block 1 handles the DivideByZeroException and displays a message stating that it is impossible to divide by zero.

It is succeeded by the second catch block, which displays an 'IndexOutOfRangeException' error indicating that the index value exceeds the permissible range.

Continuation of Loop: Subsequently, the software can proceed to the subsequent loop despite encountering an exception, allowing it to handle every item in the array.

Example 2:

The upcoming illustration illustrates the try block exception. Thus, we employ three distinct catch blocks to manage exceptions raised by try blocks. The first catch block manages IndexOutOfRangeException, the second catch block addresses FormatException, and the third catch block deals with OverflowException.

Filename: MutliCatchBlock.cs

Example

// A C# Program to implement the catch block
using System; 
class Catchblock{ 
	// Main method 
	static void Main() 
	{ 
		//The try block raises an exception
		try { 
			byte val= byte.Parse("a"); 
			Console.WriteLine(val); 
		} 
		//Catch Block 1 with IndexOutOfRangeException
		catch (IndexOutOfRangeException) { 
			Console.WriteLine("The argument value is needed"); 
		} 
		//Catch Block 2 with FormatException
		catch (FormatException) { 
			Console.WriteLine("The value entered is not a number!"); 
		} 
		// Catch Block 3 with OverflowException
		catch (OverflowException) { 
			Console.WriteLine("The data is not in the range"); 
		} 
	} 
}

Output:

Output

The value entered is not a number!

Explanation:

  • In this example, the Try block attempts to convert the string "a" into (byte.Parse("a");) by using val = byte. This line of code experiences a FormatException due to the absence of corresponding data representation for the "a" bytes.
  • Catch Block: A Catch block follows a Try block and is used to handle certain types of exceptions that a Try block can throw.
  • Catch block 1 (IndexOutOfRangeException): It handles IndexOutOfRangeException by printing the "important argument value".
  • Exception for Block 2 (FormatException): The value entered is not a numerical quantity.
  • Catch Block 3 (OverflowException): It handles the OverflowException by outputting "Data is out of range".
  • If a try block contains an exception, the program jumps to its catch block, which is determined by the type of exception thrown. In this case, the exception is of type FormatException , so control passes to catch block 2, which displays "The value entered is not a number".
  • Conclusion:

In summary, the multi-catch block manages a variety of exception types. Each individual catch block is responsible for handling multiple types of exceptions, enabling the creation of several catch blocks.

Input Required

This code uses input(). Please provide values below: