How to Rethrow Exception in C#: Syntax and Examples
In C#, you can rethrow an exception using the
throw; statement inside a catch block to preserve the original stack trace. Avoid using throw ex; as it resets the stack trace, making debugging harder.Syntax
To rethrow an exception in C#, use the throw; statement inside a catch block without specifying the exception variable. This preserves the original stack trace.
Example syntax:
try
{
// code that may throw
}
catch (Exception ex)
{
// optional handling
throw; // rethrows the caught exception
}csharp
try { // code that may throw } catch (Exception ex) { // optional handling throw; // rethrows the caught exception }
Example
This example shows how to catch an exception, log a message, and then rethrow it preserving the original stack trace.
csharp
using System; class Program { static void Main() { try { CauseError(); } catch (Exception ex) { Console.WriteLine($"Caught exception: {ex.Message}"); throw; // rethrow preserving stack trace } } static void CauseError() { throw new InvalidOperationException("Something went wrong."); } }
Output
Caught exception: Something went wrong.
Unhandled exception. System.InvalidOperationException: Something went wrong.
at Program.CauseError()
at Program.Main()
Common Pitfalls
A common mistake is to use throw ex; inside the catch block. This resets the stack trace, making it harder to find where the error originally happened.
Correct way: use throw; without specifying the exception variable.
csharp
try { // code } catch (Exception ex) { // Wrong: resets stack trace throw ex; } // Correct: try { // code } catch (Exception ex) { throw; // preserves stack trace }
Quick Reference
- throw; — Rethrows the current exception preserving stack trace.
- throw ex; — Throws the caught exception but resets stack trace (avoid).
- Use
throw;insidecatchblocks only.
Key Takeaways
Use
throw; inside a catch block to rethrow exceptions and keep the original stack trace.Avoid using
throw ex; as it resets the stack trace and hides the error origin.Rethrowing is useful when you want to log or handle an exception but still let it propagate.
Always rethrow exceptions carefully to maintain clear debugging information.