Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to throw exception without resetting stack trace?

This is a follow-up question to Is there a difference between “throw” and “throw ex”?

is there a way to extract a new error handling method without resetting the stack trace?

[EDIT] I will be trying both "inner method" and another answer provided by Earwicker and see which one can work out better to mark an answer.

like image 738
dance2die Avatar asked Apr 08 '09 14:04

dance2die


People also ask

How do I throw an existing exception?

When an exception is cached in a catch block, you can re-throw it using the throw keyword (which is used to throw the exception objects).

Can you Rethrow an exception?

Re-throwing Exceptions When an exception is caught, we can perform some operations, like logging the error, and then re-throw the exception. Re-throwing an exception means calling the throw statement without an exception object, inside a catch block. It can only be used inside a catch block.

How do you throw an existing exception in Java?

Sometimes we may need to rethrow an exception in Java. If a catch block cannot handle the particular exception it has caught, we can rethrow the exception. The rethrow expression causes the originally thrown object to be rethrown.

Should I Rethrow exceptions?

Upon determining that a catch block cannot sufficiently handle an exception, the exception should be rethrown using an empty throw statement. Regardless of whether you're rethrowing the same exception or wrapping an exception, the general guideline is to avoid exception reporting or logging lower in the call stack.


1 Answers

With .NET Framework 4.5 there is now an ExceptionDispatchInfo which supports this exact scenario. It allows capturing a complete exception and rethrowing it from somewhere else without overwriting the contained stack trace.

code sample due to request in comment

using System.Runtime.ExceptionServices;  class Test {     private ExceptionDispatchInfo _exInfo;      public void DeleteNoThrow(string path)     {         try { File.Delete(path); }         catch(IOException ex)         {             // Capture exception (including stack trace) for later rethrow.             _exInfo = ExceptionDispatchInfo.Capture(ex);         }     }      public Exception GetFailure()     {         // You can access the captured exception without rethrowing.         return _exInfo != null ? _exInfo.SourceException : null;     }      public void ThrowIfFailed()     {         // This will rethrow the exception including the stack trace of the         // original DeleteNoThrow call.         _exInfo.Throw();          // Contrast with 'throw GetFailure()' which rethrows the exception but         // overwrites the stack trace to the current caller of ThrowIfFailed.     } } 
like image 106
Zarat Avatar answered Sep 23 '22 00:09

Zarat