2.10. Error Handling


There are two main types of coding errors that programmers generally have to deal with:

  • Compile-time errors

  • Runtime errors

In VB 2005, the background compiler kicks into action every time you type in a line of code. It dynamically compiles your code and warns you of errors before you actually compile it.


In the former case, the compiler detects a syntax error and the IDE handles the error and calls it to the attention of the programmer so that immediate action can be taken to fix the problem. Runtime errors occur while an application is running. It is this type of error that must (and can) be prevented.

To ensure that an application is as robust and bug free as possible, it is important to anticipate as best you can all of the errors that might occur while your program is running. In VB 2005, error handling has been much improved over VB 6. VB 2005 now supports both structured and unstructured error handling.

VB 6 Tip: In VB 6, error handling was unstructured, performed using the primitive On Error and On Error Resume Next statements. The specific information about an error that occurred can be retrieved from the Err object.


2.10.1. Try-Catch-Finally

In VB 2005, you can implement structured error handling using the TRy… Catch…Finally construct. Basically, you place any code that could possibly trigger a runtime error, such as a disk access, into a TRy block. Any errors that happen within the try block will be caught and serviced by the Catch block(s) that follow. This is where you can take actions to correct the error or clean up any resources that you've allocated. The Finally block is executed whether an error occur in the try block or not. The Finally block is a good place to perform housekeeping chores such as closing a database or file connection.

Example 2-9 shows how you can use try…Catch…Finally statements to catch errors at multiple levels within a procedure that performs an integer division of two numbers. Note the use of multiple Catch blocks to handle exceptions that range from the specific (InvalidCastException and DivideByZeroException) to the most general (Exception).

Example 2-9. Using Try…Catch…Finally statements to handle runtime errors
 '===Error Handling=== Dim num1, num2, result As Integer Try num1 = InputBox("Please enter num1") num2 = InputBox("Please enter num2") result = num1 \ num2 MsgBox(result) Catch invalidCast As InvalidCastException     MsgBox("Please enter numbers only") Catch divisionByZero As DivideByZeroException MsgBox("Division by zero error") Catch ex As Exception MsgBox(ex.ToString) Finally MsgBox("This line is always printed.") End Try 

When the user enters a non-numeric input for one of the numbers, the InvalidCastException exception will be raised and the message "Please enter numbers only" will be printed. If the user enters a 0 for num2, it results in a division by zero error and raises the DivideByZeroException exception. The Exception exception is the root of all exceptions and will catch any exceptions not caught by the earlier Catch statements. The statement within the Finally block is always executed, regardless of whether any exception has been raised.

2.10.2. Throwing Exceptions

Besides catching errors using the try…Catch…Finally construct and the predefined exceptions available in the .NET Class Library, you can also throw your own custom exceptions by using the Throw keyword. The Throw keyword allows you to throw an exception so that you can handle the exception with the structured exception-handling code.

Consider the following example:

 Public Function divide(ByVal num1 As Single, _                            ByVal num2 As Single) _    As Single         If num2 = 0 Then Throw New _            Exception("num2 cannot be zero!")         Return num1 / num2     End Function 

In this divide function, if num2 is zero, you will throw your own exception (using the Exception class) with your own custom error message.

A user of this function can then catch the error like this:

 Try         MsgBox(divide(4, 0))     Catch ex As Exception MsgBox(ex.ToString)     End Try 

The variable ex will contain detailed information of the exception when it occurs. To display the error message, simply use the ToString method.



Visual Basic 2005 Jumpstart 2005
Visual Basic 2005 Jumpstart
ISBN: 059610071X
EAN: 2147483647
Year: 2005
Pages: 86
Authors: Wei-Meng Lee

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