Catch Unhandled Exception in C# Windows Forms

person Jason Huangfolder_openC#, Code, HOW-TOlocal_offer, , , , access_time February 27, 2012

In order to handle any exception that are not catch by your exception Handler, you need to tell .NET framework to handle it. For example, you might want to log every exception no matter what kind of exception it is.

In .NET windows Forms:
1. Must tell the Application object that you wish to handle any uncaught exceptions before any code runs.
2. Then you can setup to listen for any ThreadException on the main thread.
3. Write the code to handle the ThreadException.

1:  you need put the code in program.cs main [STAThread]

        static void Main()
            //this must be called before creating any UI Elements, 
            //in order to catch and handled any unhandled exception

2: You need to listen to any ThreadException in your Form initialization code, usually at form constructor.

public Form1()
            //catch all unhandled excepttDion
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);

3: Write the code to handle the Thread Exception, the parameter for handler e contains an Exception object):

        protected void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
            Handle(e.Exception); //Handle is a custom function to handle Exception

To test this: in your Form, throw an Exception that you do not handle in code:

private void test()
            throw new InvalidOperationException("Oh No!");

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>