Bird
Raised Fist0

Find the problem in this code:

medium📝 Debug Q7 of Q15
C Sharp (C#) - Exception Handling

Find the problem in this code:

try {
    // code
} catch (Exception ex) when (ex.Message == null) {
    Console.WriteLine("Null message");
} catch {
    Console.WriteLine("General catch");
}
AThe try block is empty
BThe when clause can cause a NullReferenceException
CCannot use Console.WriteLine in catch blocks
DThe catch without exception type is invalid after a catch with when
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the when condition

    The condition ex.Message == null accesses ex.Message, which is never null but could be empty. However, if ex was null (which it cannot be), it would cause an error.
  2. Step 2: Consider possible runtime issues

    In this case, ex.Message is safe, but if the condition was more complex and accessed properties without null checks, it could cause NullReferenceException.
  3. Final Answer:

    The when clause can cause a NullReferenceException -> Option B
  4. Quick Check:

    when condition can throw exceptions if not careful [OK]
Quick Trick: Ensure when condition is safe and null-checked [OK]
Common Mistakes:
MISTAKES
  • Assuming when condition never throws
  • Thinking catch without type is invalid here
  • Believing Console.WriteLine is disallowed

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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