Bird
0
0

What will be the output of this code?

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

What will be the output of this code?

try {
    throw new ArgumentNullException();
} catch (ArgumentException ex) when (ex.ParamName == "id") {
    Console.WriteLine("Caught ArgumentException with id");
} catch (ArgumentException) {
    Console.WriteLine("Caught ArgumentException");
}
ACaught ArgumentException
BCaught ArgumentException with id
CNo output, program crashes
DCompilation error
Step-by-Step Solution
Solution:
  1. Step 1: Check exception type and when condition

    The thrown exception is ArgumentNullException, which is a subclass of ArgumentException. The when condition checks ex.ParamName == "id", but ParamName is null by default.
  2. Step 2: Evaluate which catch block runs

    The first catch block's when condition is false (null != "id"), so it skips. The second catch block catches all ArgumentException without condition and runs.
  3. Final Answer:

    Caught ArgumentException -> Option A
  4. Quick Check:

    when false skips catch, next catch runs [OK]
Quick Trick: when false skips catch, next matching catch runs [OK]
Common Mistakes:
MISTAKES
  • Assuming when condition is true by default
  • Expecting first catch to run always
  • Confusing exception types

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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