0
0
C Sharp (C#)programming~5 mins

Throw and rethrow patterns in C Sharp (C#) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the difference between throw; and throw ex; in C#?

throw; rethrows the current exception preserving the original stack trace.<br>throw ex; throws the exception as new, resetting the stack trace to the current location.

Click to reveal answer
beginner
Why should you prefer throw; over throw ex; when rethrowing exceptions?

Using throw; keeps the original error location visible in the stack trace, which helps debugging.<br>Using throw ex; hides the original error location.

Click to reveal answer
beginner
What happens if you catch an exception and do not rethrow it?

The exception is considered handled and will not propagate further.<br>This can be useful if you want to recover or log the error without stopping the program.

Click to reveal answer
beginner
Show a simple example of rethrowing an exception preserving the stack trace.
try {
    // code that may throw
} catch (Exception ex) {
    // log or handle
    throw; // rethrow preserving stack trace
}
Click to reveal answer
beginner
What is a common mistake when rethrowing exceptions in C#?

Using throw ex; instead of throw;, which resets the stack trace and makes debugging harder.

Click to reveal answer
Which statement correctly rethrows an exception preserving the original stack trace?
Athrow ex.InnerException;
Bthrow ex;
Cthrow new Exception();
Dthrow;
What happens if you use throw ex; inside a catch block?
AThe exception is rethrown with the original stack trace.
BThe program terminates immediately.
CThe exception is rethrown but the stack trace is reset to this point.
DThe exception is swallowed and not thrown again.
Why might you catch an exception and not rethrow it?
ATo ignore the error silently.
BTo log or recover from the error without stopping the program.
CTo crash the program faster.
DTo create a new exception.
Which of these is a best practice when rethrowing exceptions?
AUse <code>throw;</code> to preserve stack trace.
BWrap exceptions in new exceptions without preserving original.
CAlways use <code>throw ex;</code>.
DNever catch exceptions.
What does the stack trace show when you use throw; inside a catch block?
AThe original location where the exception was thrown.
BThe location of the <code>throw;</code> statement.
CNo stack trace is shown.
DThe location of the catch block only.
Explain the difference between throwing and rethrowing exceptions in C# and why preserving the stack trace matters.
Think about how the error location is shown in debugging tools.
You got /4 concepts.
    Describe a scenario where you would catch an exception and choose not to rethrow it.
    Consider when you want your program to keep running after an error.
    You got /4 concepts.