Bird
0
0

What will be the output of this code snippet?

medium📝 Predict Output Q4 of 15
C Sharp (C#) - Exception Handling

What will be the output of this code snippet?

try {
    throw new Exception("Test");
} catch (Exception ex) when (ex.Message == "Test") {
    Console.WriteLine("Caught with when");
} catch (Exception) {
    Console.WriteLine("Caught without when");
}
ACaught with when
BCaught without when
CNo output, program crashes
DCompilation error
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the thrown exception and when condition

    The exception message is "Test", matching the when condition ex.Message == "Test".
  2. Step 2: Determine which catch block runs

    The first catch block's when condition is true, so it handles the exception and prints "Caught with when".
  3. Final Answer:

    Caught with when -> Option A
  4. Quick Check:

    when true triggers catch = output printed [OK]
Quick Trick: when true runs catch block, else next catch tries [OK]
Common Mistakes:
MISTAKES
  • Ignoring when condition and picking second catch
  • Expecting program crash
  • Thinking when causes compile error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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