Click here to Skip to main content
15,917,645 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
How can you make sure all exceptions are being caught in your application without try catching every possible block?
Posted

Add this in your Main() method:

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


Then add this handler:
C#
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    if (e.ExceptionObject is Exception)
    {
        // handle error
    }
}
 
Share this answer
 
v2
Comments
Hiren solanki 27-Oct-10 9:06am    
Perfect answer.
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[^]
 
Share this answer
 
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.
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900