Answer: More Exception Mysteries

Well, you folks were a lot quicker than I was… Steve got basically what I was looking for very quickly after I posted... Ben’s answer (to add his own local Exception class) was cute, but was clearly cheating as I did say no new classes…

What I was looking for exactly was:

class Program

{

    static void Main(string[] args)

    {

        AppDomain.CurrentDomain.ExceptionThrown += delegate

        {

            Console.WriteLine("Mystery inserted code");

        };

        try

        {

            Console.WriteLine("In try");

            throw new Exception();

        }

        catch (Exception)

        {

            Console.WriteLine("In catch");

        }

        Console.WriteLine("After try..catch");

    }

}

Notice I used the ExceptionThrown event while Steve and co used the CatchingException event… Both happen to work in this case. Peter and I talked about the difference between these two events… it seems that CatchingException occurs when a catch block is found for a managed exception that has been thrown, before the catch block is entered. While ExceptionThrown occurs when a managed exception is thrown, or when an unmanaged exception reaches managed code for the first time.

If you hook both of them, you see the sequence they event handlers fire in:

In try

ExceptionThrownHandler

CatchingExceptionHandler

In catch

After try..catch

Have fun!