QBasic / QB64 Discussion Forum      Other Subforums, Links and Downloads
 Return to Index  

Demo of ON ERROR to detect user input errors

November 22 2003 at 8:22 AM
  (Login Mac36)


Response to Demo of ON ERROR to detect files

FAQ014 = How can I trap errors using ON ERROR?

If you are writing a program for yourself only or to be run from the source code by skilled QBasic programmers, then you would use the following to input a number in the range -5,300):
INPUT "N% (-5 to 300)"; N%

That is great. But if you are writing a program to be run as an EXE or to be run by newbies or non-programmers, it is professional to edit the input to protect the user from goofs. Programs should not end in a STOP or QBasic-generated error except in detection of a bug in the program. All user input, however fantastic and crazy, than cannot be accepted should be rejected with a nice error message.

The simple INPUT statement will bomb out with QBasic errors. Below is the 30 or so instructions which replace that INPUT in a well-written program. It shows the need for ON ERROR to defend against the user entering 999999999999999999999999.

Mac

DECLARE FUNCTION InputN% (Min AS INTEGER, Max AS INTEGER)
DIM SHARED MyErr AS INTEGER
CLS : PRINT "Testing InputN% function"
DO
  PRINT
  DO
    LOCATE , , 1: PRINT "Enter T to test, X to exit: ";
    DO: k$ = INKEY$: LOOP WHILE LEN(k$) <> 1
    PRINT k$
    k$ = UCASE$(k$)
  LOOP WHILE INSTR("TX", k$) = 0
  IF k$ = "T" THEN PRINT InputN%(-5, 300)
LOOP WHILE k$ <> "X"
SYSTEM

GetMyErr:
MyErr = ERR
RESUME NEXT

FUNCTION InputN% (Min AS INTEGER, Max AS INTEGER)
IF Min > Max THEN PRINT "Bug in program": STOP
sMin$ = LTRIM$(STR$(Min))
sMax$ = LTRIM$(STR$(Max))
PRINT "Enter whole number in range "; sMin$; " to "; sMax$
ReadN:
LINE INPUT "Number: ", N$
N$ = LTRIM$(N$): Sign$ = ""
IF LEFT$(N$, 1) = "-" THEN MID$(N$, 1, 1) = " ": Sign$ = "-"
N$ = LTRIM$(RTRIM$(N$)): IF N$ = "" THEN GOTO ReadN
IF N$ = "0" THEN InputN% = 0: EXIT FUNCTION
IF INSTR(N$, ".") > 0 THEN PRINT "Whole number only": GOTO ReadN
FOR i = 1 TO LEN(N$)
  IF INSTR("0123456789", MID$(N$, i, 1)) = 0 THEN
    PRINT "Use digits only": GOTO ReadN
  END IF
NEXT i
MyErr = 0: ON ERROR GOTO GetMyErr
N% = VAL(Sign$ + N$): ON ERROR GOTO 0
IF MyErr > 0 THEN PRINT "Out of Range": GOTO ReadN
IF N% = 0 THEN PRINT "Unable to evaluate": GOTO ReadN
IF N% < Min THEN PRINT "Minimum is "; sMin$: GOTO ReadN
IF N% > Max THEN PRINT "Maximum is "; sMax$: GOTO ReadN
InputN% = N%
END FUNCTION

 
 Respond to this message