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!

πŸ’¬ Feedback
πŸš€ Start Learning
Share:

Tags: