Is there any global event in .NET Windows Forms and WPF applications, equivalent to On_Error in ASP.NET - Global.aspx?
Application.ThreadException
This event is raised whenever an unhandled exception occurs.
I mostly subscribe to this event, and, in the eventhandler, I log the Exception that has occured, or display a MessageBox which displays that something has gone wrong.
As mentioned by others, you can use Application.ThreadException
For user friendly Exception Handling, check this link.
[STAThread] static void Main() {
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
Application.Run(new Form1());
}
private void button1_Click(object sender, System.EventArgs e) {
throw new Exception("Whoops");
}
private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e) {
MessageBox.Show(e.Exception.Message);
}
There are basically two options to trap unhandled exceptions globally:
Application.ThreadException
forWindows.Forms
(as already pointed out by others)AppDomain.CurrentDomain.UnhandledException
The following sample program shows how to use the UnhandledException
event in C#:
class Program
{
static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Exception ex = (Exception)e.ExceptionObject;
Console.WriteLine("Unhandled exception!!");
Console.WriteLine(ex.InnerException.Message);
}
}
In addition to Application.ThreadException, you should handle AppDomain.CurrentDoman.UnhandledException. The relevant snippet from one of my program.cs files looks like this:
Application.ThreadException += new ThreadExceptionEventHandler(AppExceptionHandler.Application_ThreadException);
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(AppExceptionHandler.CurrentDomain_UnhandledException);
Edited to add: Here's a good article that explains further.
For both ASP.NET and WinForms apps, there is the AppDomain UnhandledException event:
AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf UnhandledException
In this handler, you can perform any custom logging/recovery needed:
Private Sub UnhandledException(ByVal sender As Object, ByVal e As System.UnhandledExceptionEventArgs)
Console.WriteLine(vbCrLf & "Unhandled exception:" & vbCrLf & e.ExceptionObject.ToString)
End Sub
Please note that you're not catching or handling the exception in this case: you're only receiving a notification event. Unless you end the application in your event handler, the exception will be propagated to the higher-level fault handler, which for WinForms apps will usually be in the operating system, leading to the familiar "This application has..." crash dialog.