Thottam R. Sriram Code sample · MSDN blog archive

AppDomain UnhandledException handler

blog-appdomain-unhandled-exception read the blog post →

Sample showing how to attach an UnhandledExceptionEventHandler to a sandboxed AppDomain to collect information about unexpected exceptions. program.cs throws handled and unhandled exceptions; excep.cs creates the AppDomain with an explicit PermissionSet and runs it.

Source

excep.cs C#
using System;
using System.Security;
using System.Security.Permissions;
using System.Reflection;
using System.Runtime.Remoting;
public class Sample
{
    public static void Example()
    {
        AppDomainSetup ads = new AppDomainSetup();
        ads.ApplicationBase = System.Environment.CurrentDirectory;
        PermissionSet psMain = new PermissionSet(PermissionState.None);
        SecurityPermission sec = new SecurityPermission(PermissionState.Unrestricted);
        ReflectionPermission sec1 = new ReflectionPermission(PermissionState.Unrestricted);
        FileIOPermission sec2 = new FileIOPermission (PermissionState.Unrestricted);
        UIPermission sec3 = new UIPermission (PermissionState.Unrestricted);
        psMain.AddPermission(sec);
        psMain.AddPermission(sec1);
        psMain.AddPermission(sec2);
        psMain.AddPermission(sec3);
        AppDomain md = AppDomain.CreateDomain("A", null, ads, psMain, null);
        md.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
        md.ExecuteAssembly("program.exe");
    }

    static void MyHandler(object sender, UnhandledExceptionEventArgs args)
    {
        Exception e = (Exception) args.ExceptionObject;
        Console.WriteLine("Exception Message: {0}", e.Message);
    }

    public static void Main()
    {
        Example();
    }
}
program.cs C#
using System;
using System.Security;
using System.Security.Permissions;
using System.Reflection;
using System.Runtime.Remoting;
public class Sample
{
    public static void Example()
    {
        AppDomain currentDomain = AppDomain.CurrentDomain;
        //     currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);

        try
        {
            throw new Exception("First Handled Exception");
        }
        catch (Exception e)
        {
            Console.WriteLine("Catch clause caught : " + e.Message);
        }

        try
        {
            throw new Exception("Second Handled Exception");
        }
        catch (Exception e)
        {
            Console.WriteLine("Catch clause caught : " + e.Message);
            // throw;
            // throw new Exception("Re-throw second exception", e);
        }

        throw new Exception("Un-Handled Exception");
    }

    static void MyHandler(object sender, UnhandledExceptionEventArgs args)
    {
        Exception e = (Exception) args.ExceptionObject;
        Console.WriteLine("Exception Message: {0}", e.Message);
    }

    public static void Main()
    {
        Example();
    }
}

← All posts