1

I have this standard code in my project:

try {
    myForm = new MyForm();
    Application.Run(myForm);
} catch (Exception e) {
    // handle all uncaught exceptions
}

but, when there is an unhandled exception somewhere in my program, it still shows the "default" exception handler and my catch is never hit. I want to handle certain fatal errors as known fatal errors (connection lost, for example).

Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195
  • @Jehof not quite. I don't want to catch *all* unhandled exceptions. Just some fatal ones, that can occur anywhere in the program. I still want unknown problem to be uncaught (because that gives good debugging info). – Bart Friederichs Mar 10 '14 at 08:55
  • 1
    @BartFriederichs all unhandled exceptions are fatal – Sergey Berezovskiy Mar 10 '14 at 08:58
  • @SergeyBerezovskiy I understand. I probably didn't explain it clearly. My app uses a database connection and losing it, doesn't necessarily mean fatal (I could try to reconnect for example), but I want to handle it as fatal right now. Problem is, this exception can be thrown anywhere in my program (basis of this bug is a design fault, but I cannot fix that now), so I want to catch it and make it fatal and close the application with a user friendly message. – Bart Friederichs Mar 10 '14 at 09:01
  • @BartFriederichs you should be able to catch exceptions with ThreadException if you have database operations on main thread. Also you can use UnhandledException event of AppDomain, see linked question – Sergey Berezovskiy Mar 10 '14 at 09:08

2 Answers2

1

One possibility is AppDomain.UnhandledException. Look here for more details:

Also, here is an older - but still excellent - article:

FoggyDay
  • 11,962
  • 4
  • 34
  • 48
1

You could try something like this

 myForm = new MyForm();
 Application.Run(myForm);
 Application.ThreadException +=
         new ThreadExceptionEventHandler(Application_ThreadException);

and then use this event like this

    static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
    {
      try
      {
          // Your code
      }
     catch (Exception ex)
     {
          // your code
     }
   }
Rajeev Kumar
  • 4,901
  • 8
  • 48
  • 83