Unhandled Exceptions
Avalonia does not offer any mechanism to handle exceptions globally and mark this as handled. The reason is, that one cannot know if the exception has been handled correctly and therefore the application may be in an invalid state. Instead it's highly recommend to handle exceptions locally if these can be handled by your application. That said it is still a good idea to log any unhandled exception for further support and debugging.

Logging

We recommend to log exceptions to the console, a file or anywhere else. There are several logging libraries available out there, for example Serilog and NLog.

The global try-catch

You can catch any exception from the main thread, which is also the UI thread in Avalonia, in your Program.cs-file. To do so we just wrap the entire void Main in a try and catch block. In the catch block you can log the error, inform the user, send the log file or restart the application.
1
// File: Program.cs
2
​
3
public static void Main(string[] args)
4
{
5
try
6
{
7
// prepare and run your App here
8
BuildAvaloniaApp()
9
.StartWithClassicDesktopLifetime(args);
10
}
11
catch (Exception e)
12
{
13
// here we can work with the exception, for example add it to our log file
14
Log.Fatal(e, "Something very bad happened");
15
}
16
finally
17
{
18
// This block is optional.
19
// Use the finally-block if you need to clean things up or similar
20
Log.CloseAndFlush();
21
}
22
}
Copied!

Exceptions from another thread

If you are using Tasks to run some work asynchronously, you can setup TaskScheduler.UnobservedTaskException. For more information read the Microsoft .NET-Documentation.

Exceptions from Reactive UI

If you are using Avalonia together with ReactiveUI, you can subscribe to their RxApp.DefaultExceptionHandler. For more information please refer to ReactiveUI Default Exception Handler.