Click here to Skip to main content
14,487,263 members
Rate this:
Please Sign up or sign in to vote.
See more:
How can you make sure all exceptions are being caught in your application without try catching every possible block?
Posted
Rate this:
Please Sign up or sign in to vote.

Solution 1

Add this in your Main() method:

AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);


Then add this handler:
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    if (e.ExceptionObject is Exception)
    {
        // handle error
    }
}
   
v2
Comments
Hiren solanki 27-Oct-10 9:06am
   
Perfect answer.
Rate this:
Please Sign up or sign in to vote.

Solution 2

In addition to the AppDomain.CurrentDomain.UnhandledException event if you are using a windows form then you will also need to use Application.ThreadException event. This is because windows forms already has it's own handler (ever seen the dialogue asking if you wanted to continue execution or quit?).

Also as a side note, these events will not catch all exceptions. The framework will not let you handle any AccessViolation or StackOverflow exceptions as the state of the application may have become corrupt and it would be unsafe to try and handle those errors.

In .Net 4 you can still explicitly handle some of these kinds of exceptions by using the HandleProcessCorruptedStateExceptionsAttribute[^] attribute.

AppDomain.UnhandledException[^]
Application.ThreadException[^]
   
Rate this:
Please Sign up or sign in to vote.

Solution 3

To add to topherino's and SK's answers, do not do this unless you want to show an error dialog or handle it elegantly via an error log or some such thing. Or to be more precise, do not use it to suppress unexpected errors and continue execution - that will only get your app to stay alive in various unstable conditions.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100