Bird
0
0

Consider this code:

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

Consider this code:

try {
    throw new ArgumentNullException("param");
} catch (ArgumentNullException ex) when (ex.ParamName == "param") {
    Console.WriteLine("Parameter error");
} catch (ArgumentNullException ex) {
    Console.WriteLine("Other argument null error");
}

What will be printed and why?

AParameter error, because the when condition matches the ParamName.
BOther argument null error, because when clause is ignored.
CNo output, because exception is not caught.
DRuntime error due to duplicate catch blocks.
Step-by-Step Solution
Solution:
  1. Step 1: Identify the thrown exception and its property

    The code throws ArgumentNullException with ParamName set to "param".
  2. Step 2: Check the when clause condition in the first catch

    The first catch has a when clause checking if ex.ParamName == "param", which is true, so this catch runs.
  3. Step 3: Understand catch block selection

    The second catch is ignored because the first matching catch with true when condition handles the exception.
  4. Final Answer:

    Parameter error, because the when condition matches the ParamName. -> Option A
  5. Quick Check:

    when true catches first matching block [OK]
Quick Trick: when filters catch; first true condition wins [OK]
Common Mistakes:
MISTAKES
  • Ignoring when condition and picking second catch
  • Thinking duplicate catch causes error
  • Assuming exception is uncaught

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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