views:

115

answers:

3

I would like to catch all unhandled exceptions in my UI app in C#, so that I can log them, send them by mail and restart the app.

How can I simply get this done? I tried:

try
{
 Application.EnableVisualStyles();
 Application.SetCompatibleTextRenderingDefault(false);
 Application.Run(new MainDlg());
}
catch (Exception e)
{
 Logger.Log(e);
 Logger.PostLog();
  System.Diagnostics.Process.Start("App.exe");
}

But it lets some exceptions through.

+1  A: 

You need to subscribe to the UnhandledException event in AppDomain. See http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception(VS.71).aspx

Steve Dunn
Yeah but can I catch the exceptions, make sure that the app doesn't show them to the user?
Haim Bender
+3  A: 

You can put this code in your Program.cs:

    static void Application_ThreadException(object sender,
        ThreadExceptionEventArgs e) //Generic error handler
    {
        MyApp.LogException(e.Exception); //Log exception

        BugReport frmBugReport = new BugReport();
        frmBugReport.Error = e.Exception;
        frmBugReport.ShowDialog();

        Environment.Exit(0);
    }

I'm showing an error report dialog in my app. You can chage Environment.Exit(0) with Application.Restart() (As I remember).

HasanGursoy
+1  A: 

Peter Bromberg has a good article on a variety of ways of dealing with unhandled exceptions. He describes the following approaches:

  1. Putting Application.Run() in try-catch block
  2. Using Application.ThreadException event
  3. Using AppDomain.UnhandledException event
  4. Add registry entry to pop up JIT Debugger
  5. Use ADPLUS in crash mode with debug symbols installed.

Getting Better Information on Unhandled Exceptions

About my earlier comment on the question: unless there's a pressing need to restart the crashed application - I would not automatically restart the application, because of the loop you can get stuck in. If you must restart it, present the user with a choice to restart the application before restarting. That way, if it keeps going wrong, the user can bail.

FrederikB