![]() |
VOOZH | about |
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) }
In this example, the try block generates two types of exceptions:
Each exception is handled by a specific catch block.
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.
This example demonstrates using multiple catch blocks to handle exceptions such as FormatException (invalid input format) and OverflowException (data out of range).
Number is out of range.
Important Points: