Recipe 15.3. Catching Unhandled Exceptions


Problem

Although you make judicious use of TRy…Catch and On Error statements in your code, it's possible that some exceptions will sneak through your structured and unstructured error-handling barriers. You want to keep these errors from crashing the program.

Solution

Sample code folder: Chapter 15\ UnhandledException

Handle the application-level UnhandledException event to capture any errors not dealt with elsewhere in your code. This global error handler is part of the Windows Forms Application Framework. In the Project Properties window's Application panel, make sure that "Enable application framework" is selected, and then click on the View Application Events button on that same panel. Visual Studio opens the ApplicationEvents.vb source file, which looks like this:

 Namespace My    Partial Friend Class MyApplication    End Class End Namespace 

The global error handler will appear in this MyApplication class. Select "(MyApplication Events)" from the Class Name list above and to the left of the code editor window, and then select "UnhandledException" from the Method Name list just to the right of that. Visual Studio will add a template for the UnhandledException event handler:

 Private Sub MyApplication_UnhandledException( _       ByVal sender As Object, ByVal e As Microsoft. _       VisualBasic.ApplicationServices. _       UnhandledExceptionEventArgs) _       Handles Me.UnhandledException End Sub 

Code added to this event handler will run whenever an unhandled error or exception occurs somewhere in your application. Once you have dealt with the error, you can either exit the application immediately (in a more controlled manner than just letting the program crash) or return to a basic waiting-for-input-from-the-user state. Use the e argument's ExitApplication property to indicate which choice you want to make. Setting this property to TRue, as shown here, will terminate the program:

 Private Sub MyApplication_UnhandledException( _       ByVal sender As Object, ByVal e As Microsoft. _       VisualBasic.ApplicationServices. _       UnhandledExceptionEventArgs) _       Handles Me.UnhandledException    MsgBox("An unhandled error occurred. That's bad.")    e.ExitApplication = True End Sub 

This code is never called when your application runs in the debugger.

Discussion

The solution listed above is valid only for Windows Forms applications that use the Application Framework. If you choose to disable the Application Framework, or you are writing a nonWindows Forms application, you must manually establish a global error handler for each thread of your application. We'll look at the first case here.

Create a new Windows Forms application, and clear the "Enable application frame-work" field in the Project Properties window. Open up the source code window for the Form1 form, and replace the basically empty content with the following code:

 Public Class Form1    Private Sub Form1_Click(ByVal sender As Object, _          ByVal e As System.EventArgs) Handles Me.Click       ' ----- Cause a fake unhandled error.       Throw New System.Exception( )    End Sub    Private Sub Form1_FormClosed(ByVal sender As Object, _          ByVal e As System.Windows.Forms.FormClosedEventArgs) _          Handles Me.FormClosed       ' ----- Disable the monitor before exiting.       RemoveGlobalErrorMonitor( )    End Sub    Private Sub Form1_Load(ByVal sender As System.Object, _          ByVal e As System.EventArgs) Handles MyBase.Load       ' ----- Enable error monitoring.       AddGlobalErrorMonitor( )    End Sub End Class Module Module1    Public Sub AddGlobalErrorMonitor( )       ' ----- Enable global error monitoring on this thread.         AddHandler Application.ThreadException, _          AddressOf GlobalErrorMonitor    End Sub    Public Sub RemoveGlobalErrorMonitor( )       ' ----- Disable global error monitoring on this thread.       RemoveHandler Application.ThreadException, _          AddressOf GlobalErrorMonitor    End Sub    Public Sub GlobalErrorMonitor(ByVal sender As Object, _          ByVal e As System.Threading.ThreadExceptionEventArgs)       ' ----- An unhandled global error occurred in the thread.       MsgBox("A global error was caught.")    End Sub End Module 

This code uses the AddHandler statement to connect the thread's Application. ThreadException event to a custom event handler, GlobalErrorMonitor(). It's added immediately when the (main) form is first loaded, and it remains until the form closes. Remember that this code will not work properly within Visual Studio. You must build the application and run it directly before your global exception handler can be used.

When writing console applications, monitor the System.appdomain.CurrentDomain. UnhandledException event instead of Application.ThreadException:

 AddHandler System.appdomain.CurrentDomain. _    UnhandledException, AddressOf GlobalErrorMonitor 




Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net