Bird
Raised Fist0

You want to log an exception message but still rethrow it preserving the original stack trace. Which pattern is best?

hard🚀 Application Q8 of Q15
C Sharp (C#) - Exception Handling
You want to log an exception message but still rethrow it preserving the original stack trace. Which pattern is best?
Acatch (Exception ex) { Log(ex.Message); throw new Exception(ex.Message); }
Bcatch (Exception ex) { Log(ex.Message); throw ex; }
Ccatch (Exception ex) { Log(ex.Message); return; }
Dcatch (Exception ex) { Log(ex.Message); throw; }
Step-by-Step Solution
Solution:
  1. Step 1: Identify logging and rethrowing without losing stack trace

    Logging the message and using throw; rethrows the exception preserving stack trace.
  2. Step 2: Analyze other options

    throw ex; resets stack trace, throw new Exception(...) creates new exception, and return; swallows exception.
  3. Final Answer:

    catch (Exception ex) { Log(ex.Message); throw; } -> Option D
  4. Quick Check:

    Log then throw preserves stack trace = C [OK]
Quick Trick: Log then use throw alone to keep stack trace [OK]
Common Mistakes:
MISTAKES
  • Using throw ex after logging
  • Creating new exceptions unnecessarily
  • Swallowing exceptions by returning

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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