Jeroen Landheer
Jeroen Landheer

Reputation: 9903

Handling critical exceptions in different appdomains

Let's asume the folowing bit of code, which allows you to call a class in a different AppDomain and handle almost any exception:

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace MyAppDomain
{
  class Program
  {
    static void Main(string[] args)
    {
      AppDomain myDomain = null;
      try
      {
        myDomain = AppDomain.CreateDomain("Remote Domain");
        myDomain.UnhandledException += new UnhandledExceptionEventHandler(myDomain_UnhandledException);
        Worker remoteWorker = (Worker)myDomain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, typeof(Worker).FullName);
        remoteWorker.VeryBadMethod();
      }
      catch(Exception ex)
      {
        myDomain_UnhandledException(myDomain, new UnhandledExceptionEventArgs(ex, false));
      }
      finally
      {
        if (myDomain != null)
          AppDomain.Unload(myDomain);
      }

      Console.ReadLine();
    }

    static void myDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
      Exception ex = e.ExceptionObject as Exception;
      if (ex != null)
        Console.WriteLine(ex.Message);
      else
        Console.WriteLine("A unknown exception was thrown");
    }
  }

  public class Worker : MarshalByRefObject
  {
    public Worker()
    {

    }

    public string DomainName
    {
      get
      {
        return AppDomain.CurrentDomain.FriendlyName;
      }
    }

    public void VeryBadMethod()
    {
      // Autch!
      throw new InvalidOperationException();
    }

  }
}

Now the problem is, allmost any exception can be handled, not every exception. A StackOverflowException for example will still crash the process. Is there a way to detect critical exceptions in different appdomains and handle these by unloading the AppDomain, but still allow other AppDomains to continue?

Upvotes: 9

Views: 2572

Answers (2)

Dr Spack
Dr Spack

Reputation: 181

Unfortunately a StackOverflowException cannot be caught.

See: http://msdn.microsoft.com/en-us/library/system.stackoverflowexception.aspx

... Starting with the .NET Framework version 2.0, a StackOverflowException object cannot be caught by a try-catch block and the corresponding process is terminated by default. ...

Update:

After further investigation in my old issues I found this old thread: http://www.c-sharpcorner.com/Forums/ShowMessages.aspx?ThreadID=36073

Upvotes: 2

alexn
alexn

Reputation: 58962

Since .net framework 2.0, a StackOverflowException cannot be catched using a try-catch statement.

http://msdn.microsoft.com/en-us/library/system.stackoverflowexception.aspx

Upvotes: 0

Related Questions