Catching Multiple Exceptions in .NET
π‘ Concept Name
Multiple Exception Handling in .NET
π Quick Intro
.NET allows clean handling of multiple exceptions without duplicating catch blocks using modern C# features like when
filters and pattern matching.
π§ Analogy / Short Story
Imagine you're sorting errors into folders. Instead of having a separate folder for each error type with the same content, you drop all similar issues into one shared "general issues" folderβsaving time and space.
π§ Technical Explanation
- β
Use
catch (Exception ex) when (...)
to filter types in one block. - β
C# 7+ allows
is
pattern matching:ex is X or Y
. - β
Centralize repeated logic in a shared method:
Handle(ex)
. - β C# 8+ supports switch expressions for flexible case-based logic inside catch.
π― Purpose & Use Case
- β Clean error handling for apps interacting with I/O, databases, and APIs.
- β Centralized logging for observability.
- β Reusability across large enterprise projects.
π» Real Code Example
try
{
// Risky operations
}
catch (Exception ex) when (ex is IOException || ex is SqlException)
{
Handle(ex);
}
void Handle(Exception ex)
{
Console.WriteLine($""Caught: {ex.GetType().Name}"");
// Additional logic/logging
}

β Interview Q&A
Q1: How do you handle multiple exceptions in one catch?
A: Use when
filters or pattern matching.
Q2: Whatβs the benefit of this approach?
A: Cleaner code and no duplication.
Q3: Can this be used with logging?
A: Yes β centralize logic in a shared method.
Q4: What version introduced pattern matching?
A: C# 7.0.
Q5: Is `switch` usable in catch?
A: Yes, to match exception types.
π MCQs
Q1. What keyword helps filter exception types in a catch block?
- if
- where
- when
- case
Q2. Which C# version introduced pattern matching?
- C# 5
- C# 6
- C# 7.0
- C# 8.0
Q3. What is a benefit of shared exception handlers?
- Harder to debug
- Longer code
- Code reusability
- None
Q4. How do you avoid duplication in exception blocks?
- Write longer code
- Use unsafe blocks
- Use a common handler method
- Try multiple times
Q5. Which exceptions can be grouped using `when`?
- Only IOExceptions
- Only SqlExceptions
- Any .NET exceptions
- Only system exceptions
π‘ Bonus Insight
Combine when
filters with structured logging (e.g., Serilog) to capture and categorize error types dynamically with minimal overhead.
π PDF Download
Need a handy summary for your notes? Download this topic as a PDF!