Multiple catch blocks let you handle different errors in different ways. This helps your program respond correctly to each problem.
0
0
Multiple catch blocks in C Sharp (C#)
Introduction
When you want to handle different types of errors separately.
When you want to show different messages for different problems.
When you want to fix or log errors differently based on their type.
When you want to keep your program running smoothly after an error.
When you want to avoid one big catch that hides the real problem.
Syntax
C Sharp (C#)
try { // code that might cause an error } catch (ExceptionType1 ex1) { // handle ExceptionType1 } catch (ExceptionType2 ex2) { // handle ExceptionType2 } catch (Exception ex) { // handle any other exceptions }
Each catch block handles a specific type of error.
The last catch block can catch any error not caught before.
Examples
This example catches a specific error when accessing an array out of bounds, and a general error for anything else.
C Sharp (C#)
try { int[] numbers = {1, 2, 3}; Console.WriteLine(numbers[5]); } catch (IndexOutOfRangeException ex) { Console.WriteLine("Index is out of range."); } catch (Exception ex) { Console.WriteLine("Some other error happened."); }
This example catches format errors when converting text to number, and any other errors separately.
C Sharp (C#)
try { int x = int.Parse("abc"); } catch (FormatException ex) { Console.WriteLine("Input was not a number."); } catch (Exception ex) { Console.WriteLine("Unknown error."); }
Sample Program
This program asks the user for a number, tries to divide 10 by it, and handles three types of errors: wrong input format, division by zero, and any other unexpected errors.
C Sharp (C#)
using System; class Program { static void Main() { try { Console.WriteLine("Enter a number:"); string input = Console.ReadLine(); int number = int.Parse(input); int result = 10 / number; Console.WriteLine($"10 divided by {number} is {result}"); } catch (FormatException) { Console.WriteLine("That was not a valid number."); } catch (DivideByZeroException) { Console.WriteLine("Cannot divide by zero."); } catch (Exception ex) { Console.WriteLine($"Unexpected error: {ex.Message}"); } } }
OutputSuccess
Important Notes
Order matters: catch more specific exceptions before general ones.
You can have as many catch blocks as needed.
Use the exception object (like ex) to get more info if needed.
Summary
Multiple catch blocks let you handle different errors in different ways.
Put specific exceptions first, then general ones last.
This helps your program stay clear and respond well to problems.