Introduction
One of the things that impressed me when I first started learning .NET was its enhanced exception-handling functionality. By this I mean such features as easy access to the type of exception thrown, full stack trace and inner exceptions. This makes it easy to still get full information in those places where you just catch a top-level System.Exception. I find this convenient since, if you do not need to take specific action on a particular type of exception, it is tedious to have successive catch handlers for each type of exception that may be thrown. In any case, even if you do catch specific exceptions you usually also need to catch System.Exception just to cover yourself and prevent program crashes. Thus I find that I end up catching System.Exception All Over The Place in My Code. a Typical Scenario Is That in Windows Forms and ASP.NET Web Forms Applications, All of My NON-TRIVIAL EVENT HANDLERS End Up Containing Try-Catch System.Exception Blocks.
The Trouble Is That this Does Still Clutter Up The Code Somewhat and Doesn't Really Seem Quite Right. Is there?
Better Way
A couple of months ago someone posted a message on one of Microsoft's .NET newsgroups asking just this question. In having catch System.Exception all over the place what you're really doing is a "catch-all," ie, you're Trying to catch unhandled Exceptions - Exceptions That you don't know.
One of Microsoft's developers responded to the post and pointed out that we should not use exception blocks to catch unhandled exceptions. Instead, depending on our type of application, Console, Windows or ASP.NET, we should use one of .NET's unhandled exception event handlers. This means that we'll just have one error handler to handle all unhandled exceptions. When such an exception is generated we can provide the user with the option of continuing or aborting the application.This is documented in the .NET Help but it does not really stand out in the various exception handling topics. You can find some discussion for ASP.NET in the article, Exception Management in .NET. in the discussion that follows I describe how to manage unhandled exceptions in Windows Forms applications.
Consider a Simple Windows Forms Application Containing a Single Form With Two Buttons And A Text Box. The Discussion Is In C # But a full Example Follows in Both C # and Visual Basic .NET.
The Add Button Just Adds my name to the text box. The remove button Clears It. Suppose the add button throws. Hitherto, I Would Have Done Something Like this.
private void btnAdd_Click (object sender, System.EventArgs e) {try {txtName.Text = "Kevin"; throw new InvalidOperationException ( "Invalid operation.");} catch (System.Exception ex) {DisplayError (ex);}}
(Normal, I Would Only do this means) - Typically Calling Other Non-Trivial Routines - But I'm Here Just Illustrating the process.)
But by Writing An Unhandled Exception Event Handler Delegate We can dispense with the try-catch block above. The Signature for the delegate Looks Like this.
Public Static Void Application_threadException (Object Sender, ThreadExceptionEventArgs E) {// Handle Exception. // The Exception Object Is Contained in E.Exception.} And this is how we hook it up.
static void Main () {// Subscribe to thread (unhandled) exception events // (Alternatively, could do this in Form_Load) Application.ThreadException = new ThreadExceptionEventHandler (Application_ThreadException); // Load the form Application.Run (new Form1 ( ));
So the add function can now look like this.
Private void btnadd_click (object sender, system.eventargs e) {txtname.text = "kevin"; throw new invalidopertyException ("Invalid Operation);
EXAMPLE
Here is the complete example in C # and Visual Basic .NET (with Windows Form designer generated code omitted). I have also moved the exception-handling event into an assembly-wide class so that it can be accessed by other forms. When an unhandled EXCEPTION IS AN AN ABORTIGNORERETRY DILOG IS DISPLAYD GIVING A FULL Description of the Error. of Course, in A Production Version We would Just Inform The User of An Application Error and Log The Details.
C # Implementation
Using system; using system.threading; public class form1: system.windows.forms.form {// ... (omitted) /////// [stathread] static void Main () {// Subscribe to thread (unhandled) exception events ThreadExceptionHandler handler = new ThreadExceptionHandler (); Application.ThreadException = new ThreadExceptionEventHandler (handler.Application_ThreadException); // Load the form Application.Run (new Form1 ()); .} /// /// Adds default name to text box /// private void btnAdd_Click (object sender, EventArgs e) {// Generate handled exception // Add (); // Generate unhandled exception AddWithUnhandledException ();} / //// Removes name from text box. /// private void btnremove_click (object sender, evenetargs e) {txtname.clear ();} ///// Adds default name to text box. /// throws handled Exception. /// Private Void Add () {TRY {TXTNAME.TEXT = "Kevin"; throw new invalidoperationException ("Invalid Operation.");} catch (system.exception ex) { DisplayError (ex);}} /// /// Adds default name to text box /// Throws unhandled exception /// private void AddWithUnhandledException () {txtName.Text = "Kevin";.. Throw new InvalidOperationException ( "Invalid Operation. ");} ///// Displays Exception Message. /// Private Void DisplayError (Exception EX) {MessageBox.show (ex.gettype () " / n / n " ex. measure " / N / N " EX.STACKTRACE," ERROR ", MessageBoxButtons.AbortRetryignore, MessageBoxicon.Stop;
}} // End Form1 /// /// Handles a thread (unhandled) exception. /// internal class ThreadExceptionHandler {/// /// Handles the thread exception. /// public void Application_ThreadException (object sender, ThreadExceptionEventArgs e ) {try {// Exit the program if the user clicks Abort DialogResult result = ShowThreadExceptionDialog (e.Exception);. if (result == DialogResult.Abort) Application.Exit ();} catch {// Fatal error, terminate program Try {MessageBox.show ("Fatal Error", "Fatal Error", MessageBoxButtons.ok, MessageBoxicon.Stop;} finally {application.exit ();}}} ///// Creates and Displays the Error Message. /// private dialogresult showthreadExceptionDialog (Exception ex) {string errorMessage = "unhandled exception: / n / N" ex. load "/ n" ex.gettype () "/ n / nstack trace: / n " EX.STACKTRACE; RETURN MessageBox.show (ErrorMessage," Application Error ", MessageBoxButtons.AbortRetryIgnore, MessageBoxicon.Stop);}} // end threadExceptionHandlervisual Basic .NET IMP LEMENTATION
Imports System.Threading Public Class Form1 Inherits System.Windows.Forms.Form Private Sub Form1_Load (ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load 'Subscribe to thread (unhandled) exception events Dim handler As ThreadExceptionHandler = _ New ThreadExceptionHandler () AddHandler Application.ThreadException, _ AddressOf handler.Application_ThreadException End Sub '' '' '' Adds default name to text box. '' 'Private Sub btnAdd_Click (ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnAdd.Click 'Generate handled exception Add ()' Generate unhandled exception 'AddWithUnhandledException () End Sub' '' '' 'Removes name from text box.' '' Private Sub btnRemove_Click (ByVal sender As System.Object , _ ByVal e As System.EventArgs) Handles btnRemove.Click txtName.Clear () End Sub '' '' '' Adds default name to text box. '' 'Throws handled exception.' '' Private Sub Add () Try txtName .Text = "kevin" throw new invalidopertyleException (_ "invalid operation. ") Catch ex As System.Exception DisplayError (ex) End Try End Sub '' '' '' Adds default name to text box. '' 'Throws unhandled exception.' '' Private Sub AddWithUnhandledException () txtName.Text = "Kevin" Throw New InvalidOperationException (_ "Invalid operation.") End Sub '' '' '' Displays exception message. '' 'Private Sub DisplayError (ByVal ex As Exception) MessageBox.Show (ex.GetType (). ToString ( ) & _ VBCRLF & VBCRLF & _ EXMESSAGE & VBCRLF &
vbCrLf & _ ex.StackTrace, _ "Error", _ MessageBoxButtons.AbortRetryIgnore, _ MessageBoxIcon.Stop) End Sub End Class 'Form1' '' '' 'Handles a thread (unhandled) exception.' '' Friend Class ThreadExceptionHandler '' '' '' Handles the thread exception. '' 'Public Sub Application_ThreadException (_ ByVal sender As System.Object, _ ByVal e As ThreadExceptionEventArgs) Try' Exit the program if the user clicks Abort. Dim result As DialogResult = _ ShowThreadExceptionDialog (e .Exception) If (result = DialogResult.Abort) Then Application.Exit () End If Catch 'Fatal error, terminate program Try MessageBox.Show ( "Fatal error", _ "Fatal error", _ MessageBoxButtons.OK, _ MessageBoxIcon. Stop) Finally Application.Exit () End Try End Try End Sub '' '' '' Creates and displays the error message. '' 'Private Function ShowThreadExceptionDialog (_ ByVal ex As Exception) As DialogResult Dim errorMessage As String = _ "Unhandled Exception: "_ & VBCRLF & VBCRLF & _ EXMESSAGE & VBCRLF & VBCRLF & _ EX.GETTYPE (). T oString () & vbCrLf & vbCrLf & _ "Stack Trace:" & vbCrLf & _ ex.StackTrace Return MessageBox.Show (errorMessage, _ "Application Error", _ MessageBoxButtons.AbortRetryIgnore, _ MessageBoxIcon.Stop) End Function End Class' ThreadExceptionHandlerConsole And ASP.NET APPLICATIONS
For Console Applications You Should Use The System.Appdomain.unHandledException Event. To hook it Up you Would Write:
Thread.getdomain (). UnhandledException = New UnhandledExceptionEventHandler (Application_unhandlexception);
And the event handler looks like this.public static void Application_UnhandledException (object sender, UnhandledExceptionEventArgs e) {// Handle exception. // The exception object is contained in e.ExceptionObject.}
For ASP.NET Applications You Use the system.Web.httpApplication.error Event Which is Placed in The Global.asax File. This Might Look Something Like:
protected void Application_Error (Object sender, EventArgs e) {Exception ex = Server.GetLastError (); // Stop error from displaying on the client browser Context.ClearError (); Response.Write ( "Application_Error"); Response.Write ( " Error Message: " EX.TOSTRING ());