Capture, Transfer, and Rethrow Exceptions with ExceptionDispatchInfo [.NET 4.5]
Join the DZone community and get the full member experience.
Join For Free.NET 4.5 has a little hidden gem up its sleeve – the ExceptionDispatchInfo class. It’s used by the Task Parallel Library to capture and rethrow exceptions when they are not aggregated – specifically, to support the await keyword. Luckily, the class is public and can be used by anyone to capture an exception that occurred in one context – say, a thread – and then rethrow it (selectively) in another context – say, on another thread, while maintaining the full fidelity of the original stack trace and exception information.
First, let’s take a look at a stack trace that uses ExceptionDispatchInfo to rethrow a captured exception. Given the following async method:
private static async void ThrowingMethod() { try { await Task.Run(() => { throw new InvalidOperationException(); }); } catch (Exception ex) { Console.WriteLine(ex); } }
The exception that occurs in the task is marshaled to the continuation, where it is rethrown and caught by the catch block. And here’s the output:
System.InvalidOperationException: Operation is not valid due to the current state of the object.
at VanillaCSharpConsoleApp.Program.<ThrowingMethod>b__3()
at System.Threading.Tasks.Task`1.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNot
ification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at VanillaCSharpConsoleApp.Program.<ThrowingMethod>d__5.MoveNext()
Note the bold red separator between the location where the exception was thrown and captured and the location where it was rethrown.
Now let’s try something similar in custom code – we’ll throw an exception on a thread pool thread, capture it, transfer it to the main thread, inspect it, and optionally rethrow it. It’s really easy – you use ExceptionDispatchInfo.Capture to create an ExceptionDispatchInfo instance, which can now be transferred from place to place (as long as it doesn’t cross AppDomain boundaries – the class is not serializable). Next, you inspect the captured exception using the SourceException property; and finally, you rethrow the captured exception using the Throw method.
var exceptions = new BlockingCollection<ExceptionDispatchInfo>(); ThreadPool.QueueUserWorkItem(_ => { try { Foo(); } catch (Exception ex) { ExceptionDispatchInfo edi = ExceptionDispatchInfo.Capture(ex); exceptions.Add(edi); } exceptions.CompleteAdding(); }); foreach (ExceptionDispatchInfo edi in exceptions.GetConsumingEnumerable()) { try { if (edi.SourceException.Message.Contains("invalid")) { edi.Throw(); } } catch (Exception ex) { Console.WriteLine(ex); } }
The program’s output is:
System.InvalidOperationException: This operation is, well, invalid.
at VanillaCSharpConsoleApp.Program.Bar()
at VanillaCSharpConsoleApp.Program.Foo()
at VanillaCSharpConsoleApp.Program.<>c__DisplayClass1.<Main>b__0(Object _)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at VanillaCSharpConsoleApp.Program.Main(String[] args)
What does all of this mean for practical purposes? In any situation where an exception thrown in one place has to be rethrown in another, you would typically do that by wrapping the exception with another exception. This is no longer necessary now that the original exception can be rethrown while preserving the original stack trace and exception information.
Published at DZone with permission of Sasha Goldshtein, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments