Multiple catch blocks let you handle different errors in different ways. This helps your program respond correctly to each problem.
Multiple catch blocks in C Sharp (C#)
Start learning this pattern below
Jump into concepts and practice - no test required
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.
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."); }
try { int x = int.Parse("abc"); } catch (FormatException ex) { Console.WriteLine("Input was not a number."); } catch (Exception ex) { Console.WriteLine("Unknown error."); }
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.
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}"); } } }
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.
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.
Practice
What is the main purpose of using multiple catch blocks in C#?
Solution
Step 1: Understand the role of
catchblockscatchblocks are used to handle errors that happen in thetryblock.Step 2: Recognize why multiple
Using multiplecatchblocks are usedcatchblocks lets you respond differently to different error types, making your program clearer and safer.Final Answer:
To handle different types of exceptions separately -> Option BQuick Check:
Multiple catch blocks = handle different exceptions [OK]
- Thinking multiple catch blocks speed up code
- Believing catch blocks replace try blocks
- Using catch blocks to declare variables
Which of the following is the correct syntax order for multiple catch blocks in C#?
try { ... }
catch (ArgumentNullException e) { ... }
catch (Exception e) { ... }
Solution
Step 1: Understand exception hierarchy
Specific exceptions likeArgumentNullExceptioninherit from general exceptions likeException.Step 2: Order catch blocks correctly
Place specific exceptions first so they catch their errors before the general catch block handles all others.Final Answer:
Specific exceptions first, general exceptions last -> Option AQuick Check:
Specific before general catch blocks [OK]
- Placing general catch before specific causes unreachable code
- Assuming catch order does not matter
- Trying to use multiple catch blocks without try
What will be the output of this C# code?
try {
int[] arr = new int[2];
Console.WriteLine(arr[5]);
} catch (IndexOutOfRangeException) {
Console.WriteLine("Index error caught");
} catch (Exception) {
Console.WriteLine("General error caught");
}Solution
Step 1: Identify the exception thrown
Accessingarr[5]causes anIndexOutOfRangeExceptionbecause the array size is 2.Step 2: Match exception to catch block
The first catch block matchesIndexOutOfRangeException, so it runs and prints "Index error caught".Final Answer:
Index error caught -> Option CQuick Check:
IndexOutOfRangeException triggers first catch [OK]
- Thinking general catch runs before specific
- Assuming no exception occurs
- Confusing exception types
Find the error in this code snippet:
try {
int x = int.Parse("abc");
} catch (Exception e) {
Console.WriteLine("General error");
} catch (FormatException e) {
Console.WriteLine("Format error");
}Solution
Step 1: Check catch block order
The first catch block catches allExceptiontypes, includingFormatException.Step 2: Identify unreachable catch block
SinceExceptioncatch is first, theFormatExceptioncatch block can never run, causing a compile error.Final Answer:
The FormatException catch block is unreachable -> Option AQuick Check:
General catch before specific causes unreachable code [OK]
- Putting general catch before specific
- Ignoring unreachable code errors
- Thinking finally block is mandatory
You want to handle NullReferenceException and DivideByZeroException differently, but also catch any other exceptions generally. Which is the best order of catch blocks?
try {
// code that may throw exceptions
} catch (___) {
Console.WriteLine("Null reference error");
} catch (___) {
Console.WriteLine("Divide by zero error");
} catch (___) {
Console.WriteLine("Other error");
}Solution
Step 1: Identify specific exceptions
NullReferenceExceptionandDivideByZeroExceptionare specific exceptions to catch first.Step 2: Place general exception last
The generalExceptioncatch block should come last to catch all other exceptions.Final Answer:
NullReferenceException, DivideByZeroException, Exception -> Option DQuick Check:
Specific exceptions first, general last [OK]
- Putting Exception catch first
- Mixing order of specific exceptions
- Omitting general catch block
