Bird
0
0

You want to catch an exception, add extra info, and then rethrow it preserving the original stack trace. Which pattern is correct?

hard🚀 Application Q15 of 15
C Sharp (C#) - Exception Handling
You want to catch an exception, add extra info, and then rethrow it preserving the original stack trace. Which pattern is correct?
try {
  // code
} catch (Exception ex) {
  // add info
  ???
}
Athrow new Exception("Extra info", ex);
Bthrow ex;
Cthrow;
Dthrow new Exception(ex.Message);
Step-by-Step Solution
Solution:
  1. Step 1: Understand wrapping exceptions

    To add extra info, create a new exception with the original as inner exception: new Exception("Extra info", ex).
  2. Step 2: Preserve original stack trace

    This wrapping keeps original exception details inside the new one, preserving context.
  3. Step 3: Why not other options?

    throw ex; resets stack trace, throw; rethrows original without extra info, and throw new Exception(ex.Message); loses original exception object.
  4. Final Answer:

    throw new Exception("Extra info", ex); -> Option A
  5. Quick Check:

    Wrap with new Exception and inner ex = A [OK]
Quick Trick: Wrap original in new Exception to add info and preserve trace [OK]
Common Mistakes:
MISTAKES
  • Using 'throw ex;' which loses stack trace
  • Using 'throw;' which loses added info
  • Creating new Exception without inner exception

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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