Bird
Raised Fist0

What is wrong with the following C# code snippet?

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

What is wrong with the following C# code snippet?

try {
  // some code
} catch (Exception ex) {
  // handle exception
} catch (NullReferenceException ex) {
  // handle null reference
}
AThe catch blocks are missing a finally block.
BThe catch blocks are in the wrong order; specific exceptions must come before general ones.
CThe catch blocks should not have exception variable names.
DThere is no error; the code is correct.
Step-by-Step Solution
Solution:
  1. Step 1: Review catch block order

    Specific exceptions like NullReferenceException must be caught before general Exception.
  2. Step 2: Identify error

    Here, Exception is caught first, so NullReferenceException catch is unreachable.
  3. Final Answer:

    The catch blocks are in the wrong order; specific exceptions must come before general ones. -> Option B
  4. Quick Check:

    Specific before general catch blocks [OK]
Quick Trick: Always catch specific exceptions before general ones [OK]
Common Mistakes:
MISTAKES
  • Placing general exception catch before specific
  • Assuming finally is mandatory
  • Ignoring unreachable catch blocks

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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