Jaapjan
Jaapjan

Reputation: 3385

Exception caused by AppDomain when it shouldn't?

I am working on my MCTS and currently studying the AppDomain functionality. But I am running into something unclear. AppDomain should be capturing Exception and allow the domain to safely unload. (With the possible exception of the StackOverflowException as suggested elsewhere)

AppDomainSetup setup = new AppDomainSetup();
setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
Evidence adevidence = AppDomain.CurrentDomain.Evidence;
domain.UnhandledException += new UnhandledExceptionEventHandler(domain_UnhandledException);
AppDomain domain = AppDomain.CreateDomain("MyDomain", adevidence, setup);

When I decide to create an instance of the example class in an assembly I created for this purpose I should be getting a safe, restricted Domain which will capture errors that occur and can be safely unloaded. At least this is how I understand it from my study book.

var type = (IDoSomeWork) domain.CreateInstanceAndUnwrap("Library1", "Library1.Class1");
type.Run();

This throws an exception however on type.Run() (since I made it that way). But shouldn't the AppDomain capture it safely? Isn't that why we have an AppDomain?

UPDATE:

As requested, I have included the definition of the Library1.Class1. Also, for clarity, the UnhandledExceptionEventHandler has no influence on capturing the exception and isn't relevant to the question.

[Serializable]
public class Class1 : MarshalByRefObject, IDoSomeWork
{
    public void Run()
    {
        Debug.WriteLine(AppDomain.CurrentDomain.FriendlyName);
        throw new ApplicationException(String.Format("{0}", this.ToString()));
    }
}

I have verified that it runs in MyDomain.

Upvotes: 3

Views: 369

Answers (2)

Joshua
Joshua

Reputation: 43278

 AddHandler Application.ThreadException, AddressOf MyExceptionHandler.HandleException

Adds a top-level exception handler but it might not do what you want in this case.

Upvotes: 0

Fredrik Mörk
Fredrik Mörk

Reputation: 158309

The UnhandledException event does not capture the exceptions in the traditional sense, like a try-catch block (to the best of my knowledge), it is merely an information point, allowing you to perform logging and such tasks.

Quoted from the MSDN documentation:

This event provides notification of uncaught exceptions. It allows the application to log information about the exception before the system default handler reports the exception to the user and terminates the application.

So the exception will still bubble up to the system default exception handler.

Upvotes: 2

Related Questions