DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Choosing the Right Data Transfer Protocol for Efficient Cloud Migration
  • Accepting Crypto Payments in a Classic Commerce App
  • Distribution Design Patterns in Java - Data Transfer Object (DTO) And Remote Facade Design Patterns
  • A Robust Distributed Payment Network With Enchanted Audit Functionality - Part 2: Spring Boot, Axon, and Implementation

Trending

  • Choosing the Appropriate AWS Load Balancer: ALB vs. NLB
  • Automated Testing: The Missing Piece of Your CI/CD Puzzle
  • Distributed Tracing Best Practices
  • CI/CD Docker: How To Create a CI/CD Pipeline With Jenkins, Containers, and Amazon ECS

Capture, Transfer, and Rethrow Exceptions with ExceptionDispatchInfo [.NET 4.5]

Sasha Goldshtein user avatar by
Sasha Goldshtein
·
Oct. 19, 11 · News
Like (0)
Save
Tweet
Share
8.02K Views

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.

Transfer (computing)

Published at DZone with permission of Sasha Goldshtein, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Choosing the Right Data Transfer Protocol for Efficient Cloud Migration
  • Accepting Crypto Payments in a Classic Commerce App
  • Distribution Design Patterns in Java - Data Transfer Object (DTO) And Remote Facade Design Patterns
  • A Robust Distributed Payment Network With Enchanted Audit Functionality - Part 2: Spring Boot, Axon, and Implementation

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: