Dealing with Logical Errors VB.NET

Since Visual Basic makes the handling of runtime errors a relatively straightforward process, it seems reasonable to try to mimic this process for logical errors.

Detecting Logical Errors
To detect a logical error, we place error-detection code immediately following the potential offender. For instance, consider the following procedure shell for getting a sequence of positive integers from the user, starting with the number of integers:

The proper place for error-detecting code is immediately following the InputBox function, where we can check for a nonpositive integer:

Note that the alternative to immediate detection of logical errors is to place the error-detecting code just prior to using the value of DataCt, but this is both dangerous and inefficient. It is dangerous since we might forget to place the code, and it is inefficient since we may use DataCt in a variety of locations in the program, each of which would require error-detecting code.

Where to Handle a Logical Error
Once a logical error is detected, we have three choices as to where to handle that error.

Handling the error on the spot
A logical error can be handled at the location where it was detected. Here is an example:

Handling a logical error on the spot may be appropriate when the required code is short. It is also appropriate in Property procedures, which often amount to little more than a single line that sets a private instance variable, preceded by data validation, which is essentially logical-error detection.

Handling the error in the offending procedure's error handler
We can duplicate the procedure that Visual Basic uses for runtime errors simply by raising our own runtime error. Here is an example using structured exception handling:

Note that the Exception class constructor (in one of its overloaded forms) is:
Overloads Public Sub New(String)
where String is the error message to be associated with the error. Here is an example of error raising using unstructured error handling:

Passing the error to the calling procedure
As with runtime errors, passing the error to the calling procedure can be done in a parameter of the offending procedure or as the return value of the offending function. Also, the calling procedure's error handler can be called by throwing (or raising) an error.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

VB.NET Topics