Bird
Raised Fist0

What will be the output of this code?

medium📝 Predict Output Q13 of Q15
C Sharp (C#) - Exception Handling

What will be the output of this code?

try {
    throw new InvalidOperationException("Invalid operation");
} catch (InvalidOperationException ex) when (ex.Message.Contains("Invalid")) {
    Console.WriteLine("Caught invalid operation");
} catch (Exception) {
    Console.WriteLine("Caught general exception");
}
ACaught general exception
BCaught invalid operation
CNo output
DRuntime error
Step-by-Step Solution
Solution:
  1. Step 1: Identify the thrown exception and matching catch

    The code throws InvalidOperationException with message containing "Invalid".
  2. Step 2: Check the when condition in the first catch

    The first catch has a when clause checking if message contains "Invalid" which is true, so it runs.
  3. Final Answer:

    Caught invalid operation -> Option B
  4. Quick Check:

    when condition true runs first catch [OK]
Quick Trick: Check exception type and when condition carefully [OK]
Common Mistakes:
MISTAKES
  • Ignoring the when condition and picking second catch
  • Assuming no output if when is used
  • Confusing exception types

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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