Bird
Raised Fist0

Consider this code:

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

Consider this code:

try {
    throw new Exception("Error");
} catch (Exception ex) when (ex.Message == "Warning") {
    Console.WriteLine("Warning caught");
} catch (Exception ex) when (ex.Message == "Error") {
    Console.WriteLine("Error caught");
}

What will be printed?

AWarning caught
BError caught
CNo output, exception unhandled
DCompilation error due to multiple when clauses
Step-by-Step Solution
Solution:
  1. Step 1: Analyze thrown exception message

    The exception message is "Error".
  2. Step 2: Evaluate catch blocks with when conditions

    The first catch's when condition is false ("Error" == "Warning" is false), so it skips. The second catch's when condition is true, so it runs and prints "Error caught".
  3. Final Answer:

    Error caught -> Option B
  4. Quick Check:

    when filters catch blocks, only matching runs [OK]
Quick Trick: Multiple when catches run only if condition true [OK]
Common Mistakes:
MISTAKES
  • Assuming first catch always runs
  • Thinking multiple when clauses cause compile error
  • Expecting no output

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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