-2

I've got a winforms app, and Program.cs looks something like this:

static void Main()
{
    try
    {
        // Set up application
        Application.Run();
    }
    catch (Exception ex)
    {   
        // construct log from ex
        log.Save(); // saves to db
    }
}

This is working fine, and the log is being saved to the database as required. However, the application closes afterwards.

Is there a way I can catch exceptions and log them, then continue running the application? The code above is just a sample - in reality there will be some work done if an exception is thrown.

jardantuan
  • 505
  • 1
  • 4
  • 14
  • 2
    Possible duplicate of [Catch Application Exceptions in a Windows Forms Application](http://stackoverflow.com/questions/6291933/catch-application-exceptions-in-a-windows-forms-application) – madoxdev Feb 13 '17 at 14:57
  • 1
    This is way too broad to answer without a specific code problem showing us what you are experiencing with an example. The answer obviously is, "Of course there is a way!" But that's about as good as it gets. – Bob G Feb 13 '17 at 14:58
  • 1
    possible duplicate of http://stackoverflow.com/questions/5762526/how-can-i-make-something-that-catches-all-unhandled-exceptions-in-a-winforms-a – jason.kaisersmith Feb 13 '17 at 14:58
  • 4
    This does not work fine. You only catch anything when you run with the debugger. When you shouldn't because that makes it very hard to debug exceptions. You need to delete this code. And stop assuming that you can handle exceptions when the code that threw it did not handle the exception. Exceptions are your friend, they tell you what you did wrong. Never ignore good advice. – Hans Passant Feb 13 '17 at 15:03

2 Answers2

2

Take a look at the AppDomain.FirstChanceException event.

However, you might really want to revisit your architecture; in general, you can't gracefully recover from an arbitrary Exception.

Ðаn
  • 10,934
  • 11
  • 59
  • 95
-1

You can use the Application.ThreadException event.

Before you call Application.Run, hook a delegate to the event.

Application.ThreadException += (s, e) => 
{
    // construct log
    log.Save();
}
Ian H.
  • 3,840
  • 4
  • 30
  • 60