Share this Page URL

Chapter 5. Using Visual Basic to Automat... > Handling Errors and Debugging Code - Pg. 169

Using Visual Basic to Automate Your Database 169 Types of Errors The errors you'll encounter fall into three categories: design-time errors, run-time errors, and logical errors. Design-time errors result from code that hasn't been entered correctly. For example, you might have forgotten to add End If at the end of an If...Then...Else block, or you might have mis- spelled a variable's name or assigned a value to a variable that's the wrong data type (known as a type mismatch error). The Visual Basic Editor checks much of your code as you enter it, informing you of any errors, which you can then diagnose and fix. Syntax errors are highlighted after you end a line. Syntax errors include mismatched parentheses or providing the incorrect number of argu- ments to a function. Run-time errors occur while the application is running. An example of a run-time error message is shown in Figure 5-4. This error occurred because the procedure we ran tried to open a report that doesn't exist. A run-time error would also occur if the wrong file name or path was specified in a procedure. Another example is a calculation that attempts to divide by zero or that uses a field for which some records contain Null values. (You often need to check for Null values when working with certain fields. You'll see examples of how to do this in later chapters.) Figure 5-4. An example of a run-time error that a database user would see Logic errors occur when your code doesn't perform as you intended and produces incorrect results. You might have divided or multiplied by the incorrect number, for example. Neither Visual Basic nor Access can alert you to errors of logic. These errors are difficult to detect because they don't stop the code from running. You'll see the consequences of an error in logic only when you examine the results of calculations or review data in detail. Adding Error Handling to Your Code You can control a lot by careful programming, but you can't prevent all the errors that might occur as you and others use a database. Although you can't eliminate errors, you can anticipate and handle them by adding error-handling code to your procedures. Without error-handling code, when an error occurs and the code stops, any error message that appears to a user might or might not provide a helpful explanation about what went wrong. Providing customized messages is one way to reduce possible confusion as the result of an error. Is error-handling code always necessary? If you're adding code to a database that only you will use, you'll probably have a good sense of what the code is supposed to do and can fix it if an error occurs. You might not need extensive error-handling code, but you lose nothing if you add it. If you're creating a database that other people will use, you should take time to address error-handling code in your procedures.