Sometimes when working with .NET you discover some hidden gems. Some of them very useful, other ones a little bit harder to find a good way to benefit from their functionality. One of those hidden gems that I discovered some days ago is the ExceptionDispatchInfo class. This class allows you to capture an exception that occurred in one place(e.g. a thread) and then rethrow it in another place(e.g. another thread). This seems not that special at first but what makes different is that allows you to maintain the full fidelity of the original stack trace and exception information.
How do you use this class?
Start by capturing an exception in one place by using ExceptionDispatchInfo.Capture to create an ExceptionDispatchInfo instance. This instance can now be transferred from place to place.
Next, you can inspect the captured exception using the SourceException property; and finally, you rethrow the captured exception using the Throw method.
Remark: Microsoft is using this class in the Task Parallel Library to capture and rethrow exceptions.