Shiman’s Weblog

Collecting stones from the sea-shore.

C# .NET Exceptions : Application.ThreadException

In a Windows Forms application, the windows procedure raises the Application.ThreadException event upon an unhandled exception. Subscribe to the ThreadException event to handle the unhandled exception. The subscriber is an exception handler, which prevents the application from being terminated. Do not propagate an exception caught in this manner in the unhandled exception handler. The new exception is unprotected and will likely terminate the application. After the unhandled exception handler completes, execution continues at the next message in the message pump.

Subscribe to the ThreadException event with a ThreadExceptionEventHandler delegate, which has two parameters. The object parameter is the thread object of the thread that raised the exception. The ThreadExceptionEventArg parameter of the System.Threading namespace contains the exception that was unhandled. This is the signature of the ThreadExceptionEventHandler:

ThreadExceptionEventHandler syntax:

void ThreadExceptionEventHandler(object sender, ThreadExceptionEventArgs e)

In the following code, the OnThreadException handler is added to the ThreadException event. The bthException_Click method raises an unhandled divide by zero exception. The unhandled exception is then handled in the OnThreadException method, which displays an informative message. Run the application in release mode for the expected results. Otherwise, the Visual Studio debugger intercedes the exception.

private void btnException_Click(object sender, EventArgs e)
{
    int vara = 5, varb = 0;
    vara /= varb;
}

private void Form1_Load(object sender, EventArgs e)
{
    Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(OnThreadException);
}

void OnThreadException(object sender, ThreadExceptionEventArgs e)
{
    Thread t = (Thread)sender;
    Exception threadexception = e.Exception;
    string errormessage = "Thread ID: " + t.ManagedThreadId.ToString() + " [ " + threadexception.Message + " ]";
    MessageBox.Show(errormessage);
}

November 12, 2008 Posted by shiman | C#.Net, Computer Science, OOP, Programming | , , , , , , , , , | 2 Comments