How to Bubble Up Exception Information? : Easily Explained with Examples

 You might have come across situations where we have to offload execution of some tasks to some other thread so that it can be done in the background. When this child thread is executed there might be situations where it throws exception and often these exceptions is unknown to the caller thread or the main thread. In those cases we need to bubble up the exception which is occurring in the child thread to the parent where it can be handled.

What is meant by Bubble Up Exception Information?

Bubbling up in simple terms can be related to the Air bubbles which makes its way to the surface from the bottom. In our case we are referring to the exception which occurs in the child thread to make its way up to the main thread where all the exceptions can be handled gracefully. 

There are different ways by which we can bubble up the exception information from the child thread to the main thread. In .Net 4.0 and above we can use Task through which it is much easier to achieve this as shown below:

Handling exception from Child Task

As shown in the figure above simple Try-Catch is needed to catch the exception thrown by the Task. Exception thrown is shown below:

Exception Thrown by the Task

But instead of Task if we use Thread to execute some task in the background it has to be handled differently as shown in the figure below:

Handling Exceptions thrown by Thread in the Caller Thread

As shown in the figure above we have to send the exception object to the child thread and monitor the exception object for any exception thrown once the child thread finishes its execution.

Exception handled is as shown in the figure below:

Exception handled by the caller thread

Bubbling up the Exception Information to the Calling Function

In the above scenarios we are taking about bubbling the exception from the child thread to the parent thread which creates the child thread. It can also be applied to another case where the exception information is bubbled up to the calling function from the called function. For this we can simply use the throw statement in the catch block which rethrows the exception to the calling function.

Comments

Post a Comment

Popular posts from this blog

Creating RESTful Minimal WebAPI in .Net 6 in an Easy Manner! | FastEndpoints

Step By Step Guide to Detect Heap Corruption in Windows Easily

How to dynamically add Properties in C# .NET?