Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AppDomain unhandled exceptions

There are plenty of topics covering the question. But nevertheless I have a problem.

I load the assembly into new AppDomain like this:

public void Run()
{
    //There's the problem.
    //As Panos Rontogiannis mentioned the thread is created in default AppDomain
    new Thread(RunApp).Start();
}

private void RunApp()
    try
    {
        AppDomain.CreateDomain("domain name").ExecuteAssembly("path to assembly");
    }
    catch (Exception _e)
    {
        MessageBox.Show("Unhandled Exception.\n" + _e);
    }
}

In the Main method of the loaded assembly I subscribe my handler to the UnhandledException event:

AppDomain.CurrentDomain.UnhandledException += handleException;

The handler itself:

public static void handleException(object a_s, UnhandledExceptionEventArgs a_args)
{
    var _e = (Exception)a_args.ExceptionObject;
    //Static loger class method
    Loger.WriteError(_e.GetType().ToString(), _e.Message, "default solution");
}

But wherever the exception is thrown in the loaded assembly the handler doesn't get involved. I only catch exception in the default AppDomain (first try{} catch{}).

like image 473
wazelin Avatar asked Mar 22 '13 11:03

wazelin


1 Answers

Most probably, the reason you cannot handle the exception in the new AppDomain is that it is not thrown from a thread that was created in that AppDomain. From the documentation on AppDomain.UnhandledException it is not very straight-forward to see that. The interesting part is the following:

An exception is unhandled only if the entire stack for the thread has been unwound without finding an applicable exception handler, so the first place the event can be raised is in the application domain where the thread originated.

Now if the thread that executes the code that throws, is created in your main AppDomain (like the main thread of a console app), then you should add a handler in the main AppDomain. Note though that if the type of the thrown exception is not loaded in the main AppDomain, the Assembly Loader of .NET will try to load it from your applications' base directory and probing paths. If these are not the same with the child AppDomain, then the assembly will not be resolved and an(other) exception will be thrown.

like image 130
Panos Rontogiannis Avatar answered Sep 20 '22 22:09

Panos Rontogiannis