Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing Exceptions from 3rd party component from crashing the entire application

I am writing a multi-threaded application that relies on some third party DLLs. My problem is that when using an object from the third party library, if it raises an exception while running, I am unable to catch it and it bubbles up and kills the entire application. I have many different threads each using its own object from this third party library and I need the thread that was using that copy of the object to be able to catch and deal with the exception.

Based on what I've read, it seems like most likely the 3rd party library is actually making its own threads and allowing uncaught exceptions. The .NET 2.0+ behavior allows these exceptions to kill the entire application. I'm aware of AppDomain.CurrentDomain.UnhandledException, but that does not allow you to prevent application shutdown.

For reference, I'm writing a console application in .NET 4.0. Does anyone have any solution/advice to stop these exceptions from killing my application?

like image 806
DrSpock Avatar asked May 27 '11 21:05

DrSpock


3 Answers

One thing you might look at is the HandleProcessCorruptedStateExceptionsAttribute attribute.

I don't know if this is your problem or not, but I had to recently use this attribute on a method that was calling a function in a third party COM object. This attribute is new to .net 4.0. My basic understanding is that the 4.0 framework will by default not bubble up an exception thrown in certain situations where it feels the 3rd party exception may have introduced some instabilty. I think this pertains mostly to situations where the 3rd party component is unmanaged. I am not sure, but it resolved my issue.

The usage looks like this:

[System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptionsAttribute()]
private void ThirdPartyCall()
{
    try
    {
            return Call3rdPartyFunction()
    }
    catch (Exception exInstantiate)
    {
        ...
    }
}

More information: http://msdn.microsoft.com/en-us/magazine/dd419661.aspx

like image 53
Jeremy Avatar answered Nov 11 '22 23:11

Jeremy


The issue is probably that exceptions thrown on background threads are not caught once they bubble out of the thread proc.

This seems like a non-obvious duplicate of How to prevent an exception in a background thread from terminating an application?

like image 6
hemp Avatar answered Nov 12 '22 00:11

hemp


You can stop application crash by doing this:

    AppDomain.CurrentDomain.UnhandledException += (sender, e2) =>
    {
        Thread.CurrentThread.Join();
    };

But uncaught exception from 3d party components mean that components don't do their job properly. If you don't care if they don't do the job better don't use them.

like image 1
Evgeny Gorbovoy Avatar answered Nov 11 '22 22:11

Evgeny Gorbovoy