Bird
Raised Fist0

Consider this code snippet:

hard🚀 Application Q9 of Q15
C Sharp (C#) - Exception Handling

Consider this code snippet:

try {
  // code
} catch (Exception ex) when (ex is ArgumentException) {
  Console.WriteLine("Argument exception caught");
} catch (Exception ex) {
  Console.WriteLine("General exception caught");
}

What will be printed if an ArgumentException is thrown?

ANo output, program crashes
BGeneral exception caught
CBoth messages printed
DArgument exception caught
Step-by-Step Solution
Solution:
  1. Step 1: Understand exception filters with 'when'

    The first catch block uses a filter to catch only ArgumentException instances.
  2. Step 2: Exception matches filter and is caught by first block

    The ArgumentException triggers the first catch block, printing "Argument exception caught".
  3. Final Answer:

    Argument exception caught -> Option D
  4. Quick Check:

    Exception filters catch specific exceptions [OK]
Quick Trick: Use 'when' to filter exceptions in catch blocks [OK]
Common Mistakes:
MISTAKES
  • Assuming general catch runs first
  • Thinking both catch blocks run
  • Ignoring exception filters

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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