18

I'm porting an console application to .NET Core, and I'm trying to replace this line:

AppDomain.CurrentDomain.UnhandledException += UnhandledException;

After reading this, it seems there is no built-in way to do this.

So my question: is the only way to replace this line surrounding my entire code with a try/catch?

By reading this, it seems like there is another way, namely by keep on using System.AppDomain, but I can't seem to find this class/method. My only guess was this library, but it clearly states that it should not be used if possible, so I would like not to.

VMAtm
  • 27,943
  • 17
  • 79
  • 125
Romain Vergnory
  • 1,496
  • 15
  • 30
  • 1
    Not helpful now, but this [will be back in .Net Core 1.2](https://github.com/dotnet/corefx/issues/6398) – stuartd Apr 26 '17 at 16:28
  • 1.2 was renamed to 2.0. It was supposed to ship in VS2017 but they didn't get it done in time. Current goal for "zero bugs" is May 10th. – Hans Passant Apr 27 '17 at 08:59

2 Answers2

18

You're right, the AppDomain.UnhandledException or it's analog will be available only in .Net Core 2.0, so for now you should either wait or add additional try/catch blocks. However, if you're using the tasks, you can use TaskScheduler.UnobservedTaskException, which is available from first version of .Net Core.

VMAtm
  • 27,943
  • 17
  • 79
  • 125
0

This works now, so for anyone looking to globally handle exceptions in recent versions of .NET Core (e.g., .NET 6), it's the same code used in the old .NET Framework:

class Program {
    static void Main(string[] args) {
        System.AppDomain.CurrentDomain.UnhandledException += HandleGlobalException;
        throw new Exception("Fatal!");
    }

    static void HandleGlobalException(object sender, UnhandledExceptionEventArgs e) {
        Console.WriteLine(e.ExceptionObject.ToString());
        Console.WriteLine("Press Enter to continue...");
        Console.ReadLine();
        Environment.Exit(1);
    }
}

Also works fine if your console app is using top-level statements:

System.AppDomain.CurrentDomain.UnhandledException += HandleGlobalException;
throw new Exception("Fatal!");

static void HandleGlobalException(object sender, UnhandledExceptionEventArgs e) {
    Console.WriteLine(e.ExceptionObject.ToString());
    Console.WriteLine("Press Enter to continue...");
    Console.ReadLine();
    Environment.Exit(1);
}
Tawab Wakil
  • 1,737
  • 18
  • 33