DEVELOPING EXCEPTION HANDLERS


Run-time errors, also referred to as exceptions, can occur for many different reasons. Examples include collecting and processing user input that may not be valid and attempting to access local computer and network resources that may not be available. Obviously, it would be best if your applications were written in such a way that they could handle these unexpected exceptions without blowing up or confusing your users with cryptic error messages.

In order for your applications to be able to handle exceptions, you need to anticipate the locations within your applications where errors are most likely to occur and then develop code that handles the problem. For example, if an error could occur due to incorrect user input, then you should incorporate input validation checks into your applications. If your application needs to access local network hardware resources, you should add logic that notifies the user if the required resources are unavailable. There are numerous other ways of dealing with exceptions. For example, you might:

  • Reword cryptic error messages

  • Provide the user with additional instruction

  • Apologize for the error and close down the application

  • Request that the user report the error

Visual Basic 2005 Express Edition provides two programmatic tools that allow you to establish exception handling routines, unstructured and structured. By adding exception-handling logic into your Visual Basic applications, you can attempt to prevent exceptions from creating havoc with your applications, potentially causing them to crash.

A Run-Time Exception Demonstration

To see firsthand just how Visual Basic handles exceptions, create a new Visual Basic application and modify its Load event procedure as shown below.

 Public Class Form1     Dim intX As Integer = 0     Dim intY As Integer = 10     Dim intZ As Integer     Private Sub Form1_Load(ByVal sender As System.Object, _       ByVal e As System.EventArgs) Handles MyBase.Load         intZ = intY / intX     End Sub End Class 

This application has been designed with a flaw in it that will produce an overflow error when it attempts to divide intY (10) by intx (0), because within Visual Basic, division by zero is impossible. Once you have everything keyed in, press F5 to test your application. Your application immediately runs into trouble and stops executing. Figure 11.9 shows the error message that is displayed.

image from book
Figure 11.9: An example of a typical Visual Basic run-time error.

Create an executable version of your application by saving your application, clicking on the Build menu, and selecting the Build menu item. Locate and run the executable (Release) version of your new program. When you do, the error shown in Figure 11.10 will appear. Click on Quit to dismiss the error message and stop the execution of your application.

image from book
Figure 11.10: Examining the error message generated when your application runs into an unhandled exception at run-time.

Clearly, you don't want the users of your Visual Basic applications to see error messages like these. To avoid this, you will need to test your applications extensively to make them as bug-free as possible. In situations where you cannot eliminate the possibility of an error, you will need to develop effective exception handlers.

Unstructured Exception Handlers

The first option for creating an exception handling routine is the unstructured approach, which uses the On Error GoTo statement and causes the application to redirect program flow to a specified procedure in the event an error occurs. To see how the On Error GoTo statement works, modify your application as shown below.

 Public Class Form1     Dim intX As Integer = 0     Dim intY As Integer = 10     Dim intZ As Integer     Private Sub Form1_Load(ByVal sender As System.Object, _       ByVal e As System.EventArgs) Handles MyBase.Load            On Error GoTo GenericExceptionHandler            intz = intY / intX            Exit Sub         GenericExceptionHandler:          MessageBox.Show("Error: " & Err.Description & _            ControlChars.CrLf & ControlChars.CrLf & _            "Please inform the developer of this error.")     End Sub End Class 

By adding the On Error GoTo statement at the beginning of the Load event procedure, you have instructed Visual Basic to transfer the program flow to the GenericExceptionHandler: statement in the event that an error occurs. The intZ = intY/intX statement will generate an overflow error. As a result, the next statement is skipped (Exit Sub) and the first statement located after the GenericExceptionHandler: statement (which is just a callable label embedded within the code) executes.

Whenever an error occurs, Visual Basic automatically exposes information about the error in the form of an object named Err. Using properties belonging to the Err object, such as the Description property, you can determine what type of error has occurred and try to handle it in some manner. In the previous example, the end result of adding the unstructured exception handler to the application is that the error message shown in Figure 11.11 is displayed when your application is executed.

image from book
Figure 11.11: Using an exception handler to generate a more user friendly error message.

Using the unstructured approach to set up event handlers is considered to be old school, and I don't recommend that you use it. I have provided you with an example of how the On Error GoTo statement works here just to give you a feel of what it looks like and how it works. Chances are that as you start working with other people's code, you will come across its use somewhere along the line.

Structured Exception Handlers

Microsoft's recommended approach to developing exception handlers is the structured option, which uses the TryCatchFinally statement. Using the TryCatchFinally statement, you can block off program statements where errors are likely to occur and then attempt to handle them.

To use the TryCatchFinally statement, place the statements where exceptions may occur within the Try block and then place statements designed to handle the exception in the Catch block. If different exceptions are possible, you can insert additional Catch blocks, each designed to handle a different type of exception. Lastly, you can include an optional Finally block, which will always execute, regardless of whether an execution occurred at all or which Catch block executed. When included, the Finally block is always executed last and provides a place to store any program statements that will always have to be executed.

The following example demonstrates how to apply the TryCatchFinally statement to develop an exception handler for the previous example.

 Public Class Form1     Dim intX As Integer = 0     Dim intY As Integer = 10     Dim intZ As Integer     Private Sub Form1_Load(ByVal sender As System.Object, _       ByVal e As System.EventArgs) Handles MyBase.Load         Try             intZ = intY / intX         Catch ex As OverflowException             MessageBox.Show("Error: The application has attempted " & _                "to divide a number by 0.")         Catch ex As Exception             MessageBox.Show("Error: " & ex.Message)         Finally             MessageBox.Show("Please inform the developer if any " & _               "errors occurred.")         End Try     End Sub End Class 

Trick 

The order in which Catch blocks occur is important. Visual Basic will execute the first Catch block that matches the specified criteria. When using multiple Catch blocks, always put the most specific Catch statements first, followed by the more general ones.

The statement that is likely to cause the error (a certainty in this example) is placed inside the Try block. Next, a Catch block is set up to handle the occurrence of an overflowException. Note that a variable named ex has been declared. This variable will be used to access an Exception object that Visual Basic automatically generates when an exception occurs. By examining properties belonging to this object, you can get information about the exception.

A second Catch block is set up to handle all other types of exceptions not handled by previous Catch blocks. A Finally block is then specified that will execute every time the form's Load event procedure executes, even if an exception doesn't occur.

Trick 

You can view a List of possible exceptions by typing Catch followed by a variable name and the keyword As when working with the code editor, as demonstrated in Figure 11.12.

image from book
Figure 11.12: Using IntelliSense to examine exceptions.

Although the example that I have shown you here is relatively simple, it presents you with a template that you can copy and apply when you come across the need to handle run-time errors in your applications.

Track 

When deciding whether to create an exception handler in order to attempt to deal with a potential error in one of your applications, take a look at the likelihood of the exception occurring. If it is a pretty high possibility, then you should attempt to build a new procedure to your application that deals with the situation. However, if the possibility of an error occurring is unlikely (but still possible), then adding an exception handler may be the more appropriate option.




Microsoft Visual Basic 2005 Express Edition Programming for the Absolute Beginner
Microsoft Visual Basic 2005 Express Edition Programming for the Absolute Beginner
ISBN: 1592008143
EAN: 2147483647
Year: 2006
Pages: 126

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