Getting Started
Introduction
Sample Programs
IDEs
History
Advice
Mini-Tutorial
Tutorials
Code Snippets

Resources
Web Sites
More Tutorials
Forums
Vendors/Tools
Books
Magazines
Newsletters
NewsGroups
User Groups
Talk Shows
Blogs

Controls
Overview
Button
Check3State
Checkbox
ComboBox
Frame
Graphic
Image
ImageX
ImgButton
ImgButtonX
Label
Line
ListBox
ListView
Option
Progress Bar
Scrollbar
StatusBar
TAB
TextBox
Toolbar
TreeView

GBIC >> PowerBASIC >> Tutorials >> Error Trapping

PowerBASIC Information Center Tutorials
These tutorials were written to help you get a quick, but thorough, understanding of PowerBASIC - the scope of the language as well as it's specific capabilities.

Introduction       Projects       Language           Messages       Functions           Advanced
  • Overview
  • Examples
  • IDE
  • Compilation
  • Distribution
  • Project Files
  • DDT Windows
  • Controls
  • Menus
  • Dialogs  
  • Help Files
  • Resources  
  • Templates  
  • Project Shell  
  • Syntax
  • Operators
  • Data Types
  • Variables
  • Scope
  • Declarations  
  • Procedures
  • Flow Control
  • Windows
  • Messages
  • Callbacks
  • Mouse
  • Keyboard
  • Dialogs
  • Controls
  • Subclassing
  • Arithmetic
  • Trig  
  • Strings
  • Arrays
  • Date/Time
  • Printing
  • Files
  • Folders
  • Keyboard
  • Mouse
  • Sound
  • System
  • Error Traps
  • Debugging
  • Objects
  • Graphics
  • Databases
  • API
  • DLLs
  • ASM
  • Threads
  • Error Trapping
    The PowerBASIC philosophy of generating tight, fast code has resulted in elimination of much (but not all) automatic error trapping. Trapping means detecting when an error occurs, providing error information to the program, running designated code in response to the program and preventing the program from termination early.

    The elimination of (most) error trapping by PowerBASIC means that when most errors occurs (such as divide by zero), PowerBASIC does not stop operation, it does not display an error message, it does not set error variables (such as ERR - see below). It just continues execution with no warning to the programmer. The results of the statements and variable involved will be undefined and will likely result in the program giving unexpected results.

    However, some errors are so serious that Windows will force the program to stop - a General Protection Fault (GPF). Some GPFs can even cause the PC to shut down and reboot!

    Fortunately, PowerBASIC provides several ways for a programmer to trap run-time errors to prevent unexpected results or untimely termination of the program. Here's a categorized list of the PowerBASIC error functions.

      • Most Recent Error Info
       erl, erl$, err, errclear, error$ 
      • Generate Error
       error 
      • Respond to Errors
       On Error, resume, Try/End Try 

    The tutorial on debugging provides additional information on PowerBASIC capabilities for identifying errors with program code.

    Exceptions to Error Detection
    PowerBASIC does detect disk access violations. The types of errors detected are listed further down this page, under "Run-Time Errors".

    PowerBASIC programs can also detect out-of-bounds array, pointer access, and memory allocation failures - but only when the compiler directive #DEBUG ERROR ON is used. It is OFF by default.

    Trapping Run-Time Errors
    Instead of simply letting an application crash when a run-time error occurs, a programmer can make use of two PowerBASIC tools for handling errors which happen while the program is running.

    Normally, the goal of a programmer is to monitor inputs from users, or the system, and to prevent the occurrence of errors. However, that may not always be possible, in which case the programmer can turn to one of the following methods of capturing an error and continuing to execute code that works around the error.

    • On Error/Resume
      The On Error GoTo enables error trapping. That means that when an error is detected, PowerBASIC to jump to the named line of code (line number or label) and continue execution from that point.

      Consider what happens in the next example application, which does not have error trapping. If the filename entered by the user does not exist, the Open statement fails with an error. Without an error trap, the error is ignored, except that the PowerBASIC error functions (err, error$, erl, erl$) are set. The next line is executed, a% is set to 5, and the program ends.

          Function PBMain () As Long
              f$ = InputBox$ "Filename?: ",,"") ' ask user for filename
              Open "xx.xx" For Input as #1      ' error if not exist
              a% = 5                            ' executes regardless of error
          End Function
      

      The error functions could be examined at this time to check for an error. However, the next example shows how to have PowerBASIC respond automatically to the error.

      The first line adds error trapping by adding the On Error statement. If the Open statement fails to find the file, an error is generated. Because the On Error statement is present, PowerBASIC jumps to the line labeled "mistake" and continues execution. At that point, a messagebox displays the error message found in Error$. When the messagebox is dismissed, the application ends.

          Function PBMain () As Long
              On Error GoTo mistake             ' mistake is a label name
              f$ = InputBox$ "Filename?: ",,"") ' ask user for filename
              Open "xx.xx" For Input as #1      ' error if not exist
              a% = 5                            ' executes if not error
              Exit Function
      
              mistake:             ' on error, execution continues here
              MsgBox Error$        ' error displayed
          End Function
      

      Rather than simply display the error message, the program would normally react to the error, perhaps by asking the user for another filename. The point is that by using On Error the program traps the run-time error and executes specified code in response to the error. The programmer has to decide what response is appropriate, but the opportunity to respond is made possible by the use of On Error.

      Two variations of the On GoTo statement are provided by PowerBASIC.

          On Error Resume Next
          On Error GoTo 0
      

      The Resume Next simply tells PowerBASIC to ignore the error and continue execution with the line following the one where the error occurred. This statement would be used instead of the GoTo xx statement, telling PowerBASIC that there is no error trapping code to execute.

      The GoTo 0 turns off error trapping. This statement can be inserted at any point in the procedure to disable any future response by PowerBASIC to an error.

      Finally, a RESUME statement may be included within the error trap code. If used, the resume jumps to the directed location. Next refers to the line of code following the one where the error occurred. Label refers to any source code line within the procedure with the specified label or line number.

          Resume next
          Resume Label
      

    • Try/End Try
      The second approach to trapping errors is to create a Try/End Try named block of code. This technique provides a very structured approach to error trapping, keeping all of the code tightly positioned for easy debugging (the On GoTo can be visually difficult to work with, since the error trap code can be offscreen at the bottom of a long procedure).
          TRY
          ... statements1
          CATCH
          ... error handler statement2
          FINALLY                          'optional
          ... statements3
          END TRY
      

      When a Try/End Try code block is reached in a program, the TRY statements are executed normally. If an error occurs in that code, the CATCH statements are executed. If not error occurs, the CATCH statements are ignored.

      Regardless of whether an error occurs, the statements in the optional FINALLY section are executed.

      Here's the Try/End Try code again, with some actual statements. The file name "xxx.xxx" won't exist and so an error occurs, causing the Catch statement to be executed. The single line of Finally code will execute regardless of whether an error occurred or whether the Catch statements were executed.

          Try
              Open "xxx.xxx" For Input As #1
          Catch
              MsgBox "Error: xxx.xxx not found!"
          Finally
              MsgBox "no matter what"
          End Try
      

      Try levels can be nested. Because of that the ERR value is local to the Try structure. Whatever ERR was before the Try structure was entered, will be restored on the Try structure is exited.

      While not prevented, PowerBASIC discourages exiting a Try structure except by passing through the Exit Try statement.

      On Error GoTo can be used in the same procedure as a Try structure, but not within a Try structure.

    Once an error is trapped within PowerBASIC (using either of the techniques above), PowerBASIC makes information about the error available to the program, as discussed in the next section.

    Information About Run-Time Errors
    When an error is trapped, there are four pieces of information that PowerBASIC makes available to the programmer:

    • ERL - line number
    • ERL$ - last named code block
    • ERR - error code
    • ERROR$ - error description

    ERL returns the last numbered line that was executed before the error. If lines are not numbered, ERL returns zero. It does not return the simple physical position of the source code line within the program.

    ERL$ extends the capability of ERL, covering not only the last numbered line but the last label or procedure executed prior to the error. Only a single value is returned - whichever of the three is closest to the line where the error occurred.

    ERR returns the error code can be used to look up a description of the error, as shown in the table of trappable run-time error codes that is listed further down this page. Another PowerBASIC error function ERRClear can also be used to retreive the error code. However, then ERRClear is used, it also clears ERR.

    ERROR$ provides a description that matches the error code - just like the table below but available to the application so that it can display the error to users as an aide to debugging.

    Simulating Errors - ERROR
    When writing a program a programmer needs to see if the program can handle errors. One approach is to write code that causes a real error. However, it's simpler to use the ERROR statement, which causes a specified run-time error to be generated.

    Error Trapping Points to Remember
    Remember that PowerBASIC simply does not trap numeric errors. If a division by zero occurs, the use of an On Error will not work because PowerBASIC does not trap the error. The programmer must detect/test, and then correct, the conditions that would cause an error.

    PowerBASIC does capture all file I/O errors and using the On Error statement will allow a program to respond to the error by executing specified code.

    Error trapping is local to a procedure. The target of a GOTO must be in the same procedure as the GOTO statement.

    Error trapping cannot occur in an expression.

    Error trapping for array out-of-bounds and null-pointer values can be trapped, but only if the compiler directive #DEBUG ERROR ON is used. This is often used during program development but then removed for production software.

    Run-Time Errors Here's a listing of the pre-assigned run-time errors.
    • 0 - no error
    • 5 - illegal function call
    • 6 - overflow
    • 7 - out of memory
    • 9 - subscript/pointer out of range
    • 11 - division by zero
    • 24 - device time-out
    • 51 - internal error
    • 52 - bad file name/number
    • 53 - file not found
    • 54 - bad file mode
    • 55 - file already open
    • 57 - device I/O error
    • 58 - file already exists
    • 61 - disk full
    • 62 - input past end
    • 63 - bad record number
    • 64 - bad file name
    • 67 - too many files
    • 68 - device unavailable
    • 69 - COMM error
    • 70 - permission denied
    • 71 - disk not ready
    • 72 - disk media error
    • 74 - rename across disks
    • 75 - path/file access error
    • 76 - path not found
    • 99 - object error
    • 241 - global memory corrupt
    • 242 - string space corrupt

    Error Trapping Function Summary

    • ERL - line number of error
    • ERL$ - last named code block (label/line#/procedure)
    • ERR - error code
    • ERRCLEAR - error code OR clear error code
    • ERROR - generate specific run-time error (sets ERR)
    • ERROR$ - error description
    • ON ERROR - set error-trapping routine
    • RESUME - continue execution after error handling with ON ERROR GOTO
    • TRY/END TRY - structured error trapping/response

    Error Trapping Function Reference
    Here's a quick reference of the available error trapping functions, in alphabetical order.

    • ERL -
          iLine& = ERL           'last numbered line
          

    • ERL$ -
          Line& = ERL$          'last named code block
          

      Only the first 8 characters of the code block name will be retreived.

    • ERR -
          iError% = ERR         'gets error number
          

    • ERRClear -
          iError% = ERRClear    'gets error number AND clears ERR
          ERRClear              'clear the error
          

    • ERROR -
          ERROR 12              'generate error #12
          

      Use error values 1-255.

    • ERROR$ -
          desc$ = ERROR$        'description of error
          

    • On Error -
          Function PBMain () As Long
              On Error GoTo mistake             ' mistake is a label name
              f$ = InputBox$ "Filename?: ",,"") ' ask user for filename
              Open "xx.xx" For Input as #1      ' error if not exist
              a% = 5                            ' executes if not error
              Exit Function
      
              mistake:             ' on error, execution continues here
              MsgBox Error$        ' error displayed
          End Function
          

      This code is discussed further up the page.

    • Resume -
          Resume Next                 'continue at line following error
          Resume label                'continue at specified line
          

    • Try/End Try -
          Try
              Open "xxx.xxx" For Input As #1
          Catch
              MsgBox "Error: xxx.xxx not found!"
          Finally
              MsgBox "no matter what"
          End Try
      

      This code is discussed further up the page

    If you have any suggestions or corrections, please let me know.