AppDomain.CurrentDomain.UnhandledException Not working on main thread.

I’m trying to create a global exception handler for my Unity project and would like to have a reference to the Exception to do some special handling.

I’m using AppDomain.CurrentDomain.UnhandledException to catch the exceptions

public void Start()
   {
      AppDomain currentDomain = AppDomain.CurrentDomain;
      currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);

      throw new Exception("1");
   }

   static void MyHandler(object sender, UnhandledExceptionEventArgs args)
   {
      Exception e = (Exception) args.ExceptionObject;
      Debug.Log("MyHandler caught : " + e.Message);
   }

If an exception is thrown on a different thread I receive the event and my handler is called, but if an exception is thrown on the main thread my handler is never called.
Is there a way I can capture unhandled exceptions made on the main thread using AppDomain.CurrentDomain.UnhandledException?

2 Likes

Not related to main thread, but

I found that for Tasks, one also has to register TaskScheduler.UnobservedTaskException.

Example:

private void Start()
{
    TaskScheduler.UnobservedTaskException += OnUnobservedTaskException;
    Task.Run(() =>
        {
            Debug.Log($"Running task on thread {Thread.CurrentThread.ManagedThreadId}");
            throw new Exception($"Dummy exception on task on thread {Thread.CurrentThread.ManagedThreadId}");
        });
}

private void OnUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
{
        Debug.Log($"UnobservedTaskException on thread {Thread.CurrentThread.ManagedThreadId}: {e.Exception}");
        Debug.LogException(e.Exception);
}

In contrast, AppDomain.UnhandledException did not receive the Exception from the Task.

So I highly recommend to set TaskScheduler.UnobservedTaskException if you are making use of Taks (note that third-party libraries also may use Tasks).