1

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.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
Haim Bender
  • 7,937
  • 10
  • 53
  • 55
  • 3
    With an approach like that, there is an edge case that your application blows up with an exception on startup and then restarts only to blow up again. The user will have application that keeps relaunching itself very quickly and is rather hard to kill even with the task manager. This will be problematic to most users. You may want to guard against this with some kind of counter mechanism, although of course that could throw an exception again. For that mechanism, if any exception happens, throw a particular exception, which doesn't get handled by the exception handler that restarts the app. – Frederik Jul 10 '10 at 09:01
  • @FrederikB : thanks for pointing out this design flaw. – apoorv020 Jul 10 '10 at 13:27

3 Answers3

3

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).

HasanG
  • 12,734
  • 29
  • 100
  • 154
2

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.

Frederik
  • 2,921
  • 1
  • 17
  • 26
1

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
  • 21,044
  • 11
  • 62
  • 87