Bird
0
0

Why might a developer prefer using a when clause in a catch block instead of nested if statements inside the catch block?

hard🧠 Conceptual Q10 of 15
C Sharp (C#) - Exception Handling

Why might a developer prefer using a when clause in a catch block instead of nested if statements inside the catch block?

ABecause <code>when</code> clauses prevent exceptions from propagating
BBecause <code>when</code> clauses allow catching multiple exceptions at once
CBecause <code>when</code> clauses automatically log exceptions
DBecause <code>when</code> clauses filter exceptions before entering the catch block, improving clarity and performance
Step-by-Step Solution
Solution:
  1. Step 1: Understand difference between when and if inside catch

    A when clause filters exceptions before the catch block runs, so only matching exceptions enter the block.
  2. Step 2: Benefits of filtering early

    This improves code clarity by separating filtering logic from handling logic and can improve performance by avoiding unnecessary catch block execution.
  3. Final Answer:

    Because when clauses filter exceptions before entering the catch block, improving clarity and performance -> Option D
  4. Quick Check:

    when filters early, if filters inside catch [OK]
Quick Trick: when filters exceptions before catch block runs [OK]
Common Mistakes:
MISTAKES
  • Thinking when catches multiple exceptions simultaneously
  • Assuming when logs exceptions automatically
  • Believing when stops exception propagation

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More C Sharp (C#) Quizzes