Reputation: 1598
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.
Upvotes: 18
Views: 9815
Reputation: 2313
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);
}
Upvotes: 1
Reputation: 28345
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
.
Upvotes: 18