Directives

Chapter 10. Exception Handling

The grandest of intentions and the most thorough planning can't eliminate errors in code. Errors can be programmer errors (usually caused by bad assumptions, such as that a denominator will never be 0) or environmental errors (such as an attempt to save a file that is too large for the amount of free space on a disk). You should strive for error-free code, but you should also create every procedure with the assumption that an error might occur. This means that every procedure must contain an error handler.

There are practically an infinite number of possible program errors, but they basically fall into two types: compile (build) errors and run-time errors (called exceptions). A build error is an error that prevents Microsoft Visual Basic's compiler from compiling the code; Visual Basic won't execute a procedure that has a compile error in it, and you can't distribute a run-time version of an application that has a compile error. Most compile errors are a result of erroneous syntax.

For example, if you attempt to call a procedure defined as

Public Sub MyProcedure(ByVal intMyVariable As Integer) 

by using the statement below, a compile error occurs because of the added argument in the Call statement.

Call MyProcedure(intVariable1, intVariable2) 

Run-time errors occur while a program is running and are usually the result of trying to perform an invalid operation on a variable. For instance, the following code doesn't generate a compile error.

Dim intNumerator As Integer Dim intDenominator As Integer Dim intResult As Integer  ' Modify variables here  intResult = intNumerator / intDenominator 

Under most circumstances, this code won't even generate a run-time error. However, if the value of intDenominator is 0, Visual Basic throws an exception because the result of 10 divided by 0 (which Visual Basic treats as infinity) can't be placed into an Integer. If a run-time error occurs when you run a project in the integrated development environment (IDE), code execution stops at the offending line and an error message appears. In a compiled program, an unhandled exception is fatal, causing the entire application to crash to the desktop (without calling any necessary clean-up code, I might add). You can prevent execution from stopping when run-time exceptions occur by creating exception handlers.



Practical Standards for Microsoft Visual Basic. NET
Practical Standards for Microsoft Visual Basic .NET (Pro-Developer)
ISBN: 0735613567
EAN: 2147483647
Year: 2005
Pages: 84

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