Search code examples
c#.netexception

Global exception handler with UnhandledExceptionEventArgs not working


After reading this MSDN page, I've created a global exception handler in my .net class library, for logging purposes, which looks like this:

    static void OnException(object sender, UnhandledExceptionEventArgs args)
    {
        Exception ex = (Exception)args.ExceptionObject;
        Logging.LogException(ex);
    }

But then if I throw new UnauthorizedAccessException() or throw new Exception() from a method, this does not catch it at all.

The MSDN page says:

UnhandledExceptionEventArgs provides access to the exception object and a flag indicating whether the common language runtime is terminating. The UnhandledExceptionEventArgs is one of the parameters passed into UnhandledExceptionEventHandler for the AppDomain.UnhandledException event

I believe what I'm doing falls under the AppDomain (and not ThreadException)? What am I doing wrong here?

PS. I'm trying to avoid a try-catch block, since apparently it's bad practice. This class library is called from a windows service which runs periodically so I'd rather not let it 'crash' to avoid memory leaks due to unforeseen exceptions and would prefer to monitor the event logs regularly.


Solution

  • You will need to install the exception handler in the current app domain in order for it to fire:

    AppDomain.CurrentDomain.UnhandledException += OnException;
    

    Otherwise its just a method declaration that will never be called.