Error Handling


In any application, one challenge faced by developers is dealing with the inevitable errors that pop up. Application errors come in three varieties:

  • Syntax errors Syntax errors include misspelled or missing keywords (such as a missing End If statement), or other mistakes relating to the syntax of the language you’re using. Syntax errors are typically flagged by the IDE and can be easily fixed at design time.

  • Run-time errors Run-time errors appear once your code is compiled and running. Run-time errors are caused by code that appears correct to the compiler but cannot run with certain values. For example, code that divides one integer variable by another will appear to be correct to a compiler, but it will cause a run-time error if the second variable is zero. Run-time errors can also occur when a user gives an unexpected response to a program or when the system is not in a state consistent with what the program expects, such as not having a disk in the floppy disk drive when a program is expecting to read from it.

  • Logic errors Logic errors are errors in which a program that works correctly under some (or most) circumstances gives unexpected or unwanted results based on certain input values. This type of error can be extremely difficult to track down and fix because it doesn’t stop the execution of the program.

One thing that all three types of errors have in common is that they must all be handled in some fashion, lest they provoke grave dissatisfaction on the part of your users. An important first step is prevention. In Visual Basic .NET, you can use Option Explicit and Option Strict in your applications to prevent some run-time errors. (They’re both turned on by default in the Visual Studio .NET IDE.) Using Option Explicit will raise a syntax error if you attempt to use a variable before declaring it, which can help greatly if you have a habit of misspelling variable names. Using Option Strict will raise a syntax error if you attempt an implicit data type conversion that would result in a loss of data. Option Strict also implies Option Explicit, so Option Strict will also raise a syntax error on any attempt to use an undeclared variable.

The following example demonstrates the use of Option Strict:

Option Strict On Dim MyInt As Integer Dim MyDouble As Double MyDouble = 3.14159 MyInt = MyDouble 'This line will cause an error at compile time

Both Option Explicit and Option Strict must come before any other code in the module in which they appear.

Using the On Error Statement

Once you’ve taken the preventive steps of using Option Explicit, or better yet, Option Strict, it’s time to look at handling those inevitable errors. Error handling, also known as exception handling, is another type of flow control that allows you to execute code that you specify when an error or exception occurs. In Visual Basic 6, the only available option for error handling was setting up an error handler using the On Error statement. That option still exists in Visual Basic .NET:

Sub ExampleSub(ByVal Arg1 As Integer, ByVal Arg2 As Integer) On Error GoTo ErrorHandler 'Code that might cause an error Exit Sub ErrorHandler: 'Error handling code Resume Next End Sub

The On Error statement transfers execution to the section of code indicated by the ErrorHandler label. Once the error-handling code has executed, the Resume Next statement causes execution to return to the statement immediately following the line that caused the error. The Exit Sub statement appearing just prior to the ErrorHandler label prevents the error handler from running if no error occurs.

The On Error statement is an example of unstructured error handling. Applications using unstructured error handling are generally more difficult to debug

and maintain. Fortunately, Visual Basic .NET now also supports structured exception handling using the Try…Catch…Finally syntax.

Note

You might see the terms error and exception used interchangeably. In .NET, exceptions are unexpected events that occur during the execution of your code. They differ from errors in that each exception is represented by an instance of an exception class (there are many types of exception classes, each derived from the base System.Exception class), which provides developers with properties and methods that allow them to deal with the exception.

Using Structured Exception Handling: Try…Catch…Finally

The Try…Catch…Finally form of exception handling, also known as structured exception handling, should be familiar to C++ and Java developers. C#, a language with origins in C/C++, also supports structured exception handling. This form of exception handling is new to Visual Basic developers.

In Visual Basic .NET, the Try…Catch…Finally syntax allows you to enclose code that might cause an exception in such a way as to catch and deal with specific exceptions and/or provide generic exception handling. The following code shows a simple Try…Catch block:

Dim a, b, c As Integer Try 'Start monitoring for exceptions 'Code that may cause an exception a = 1 b = 0 c = a / b Catch OE As OverflowException 'Code to handle exception Finally 'Code that executes after any code in the Catch block(s) End Try

You can define Catch blocks for as many specific errors as you want to handle. You can use the Finally block for any code you want to run after the exception- handling code, including clean-up code, such as code to close a file. The Finally block of code is always run, whether or not an exception has occurred.

In addition to catching exceptions, your code can actually throw an exception (cause an error). To do so, you use the Throw keyword. For example, if you wanted to catch only the divide by 0 exception and then rethrow any other exception (for example, to have a higher-level exception handler handle a particular type of exception), you could use the following code:

Dim a, b, c As Integer Try 'Start monitoring for exceptions 'Code that may cause an exception a = 1 b = 0 c = a / b Catch OE As OverflowException 'Code to handle divide by 0 exception Catch e As Exception Throw(e) 'Rethrow exception e Finally 'Code that executes after any code in the Catch block(s) End Try

It is worth noting that the most specific Catch blocks should be first, followed by any more general Catch blocks. If the Catch for the most general exception type (Exception in this example) was first, all exceptions would be caught in that block, including the more specific exception, OverflowException.

What happens if an exception is thrown and your code does not catch it? If custom errors are not enabled (as I’ll discuss in Chapter 5), the exception details are displayed to the user, which is probably not what you want to happen. This next example will walk you through the process of creating a page that generates an unhandled exception, and then adding exception handling to properly handle the exception.

start example

Handle an exception

  1. Open Visual Studio .NET.

  2. From the File menu, select Open, and then select Open Project. Select the Chapter_03 project you created earlier in this chapter. You can also select this project by choosing File, then Recent Projects.

  3. Right-click the Chapter_03 project in the Solution Explorer. From the context menu, select Add, then Add Web Form. When prompted, type the name of the form as Exceptions.aspx, and then click Open.

  4. From the Toolbox, on the right side of the screen, select a button and drag it to the form.

  5. Select a label and drag it to the form just below the button.

  6. Using the Properties window on the right-hand side of the screen, change the Text property for the button from Button to Divide By Zero. The button conveniently expands to show all of the entered text. The screen should look similar to the illustration on the following page.

    click to expand

  7. Change the ID of the label from Label1 to Message.

  8. Double-click the button in the designer.

    The code-behind module for the page will be loaded for editing, and the Button1_Click event handler will be added.

  9. Add the following code to the handler:

    Dim a, b, c As Integer a = 1 b = 0 c = a / b Message.Text = c.ToString
  10. On the File menu, click Save All to save the page, and then select Build Chapter_03 from the Build menu to compile the project.

  11. Test the page by right-clicking Exceptions.aspx in Solution Explorer, and then selecting View In Browser. When you see the screen with the Divide By Zero button, click the button. You will see a screen similar to the illustration on the following page, in which the Output window is closed to allow you to see more of the page.

    click to expand

  12. Close the embedded browser window, locate the Button1_Click handler in Exceptions.aspx.vb, and then change the code in the handler to the following:

    Dim a, b, c As Integer Try 'Start monitoring for exceptions 'Code that may cause an exception a = 1 b = 0 c = a / b Catch OE As OverflowException 'Code to handle exception Message.Text = "Overflow from dividing by zero." End Try

  13. Select File, then Save All to save the page, and then select Build Chapter_03 from the Build menu to compile the project.

  14. Test the page using the same process as in step 9. Clicking the button should give you a result similar to the illustration on the following page.

    click to expand

end example




Microsoft ASP. NET Programming with Microsoft Visual Basic. NET Version 2003 Step by Step
Microsoft ASP.NET Programming with Microsoft Visual Basic .NET Version 2003 Step By Step
ISBN: 0735619344
EAN: 2147483647
Year: 2005
Pages: 126

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