Author Topic: Re: ON ERROR and integer division by zero?  (Read 1269 times)

0 Members and 1 Guest are viewing this topic.

Offline bplus

  • Global Moderator
  • Forum Resident
  • Posts: 8053
  • b = b + ...
    • View Profile
Re: ON ERROR and integer division by zero?
« on: December 15, 2018, 10:48:33 am »
Maybe division by zero build into math routines, this uses the error trap (in my Windows 10 system, whereas I also get "Division by zero" with your code):
Code: QB64: [Select]
  1. OPEN "../hello/hello.txt" FOR INPUT AS #1
  2. PRINT "hello world"
  3. 999 PRINT "<error>": RESUME NEXT
  4.  
  5.  

BTW the error message with Division by zero is titled a "Critical Error"
« Last Edit: December 15, 2018, 10:53:55 am by bplus »

Offline Pete

  • Forum Resident
  • Posts: 2361
  • Cuz I sez so, varmint!
    • View Profile
Re: ON ERROR and integer division by zero?
« Reply #1 on: December 15, 2018, 11:18:54 am »
I would consider that a bug, but I cannot recall if QuickBASIC could process division by zero through an error handler or not. If it could, QB64 should be able to trap it, too.

Your example uses integer division, so it means anything less thna or equal to .5 will end up being division by zero.

To solve and since division would usually occur with variables, all you need to do is false trap the denominator ...

Code: QB64: [Select]
  1. INPUT "Denominator: "; d
  2. IF d <= .5 THEN
  3.     LOCATE -1
  4.     PRINT 1 \ d
  5. 999: PRINT "<error>": RESUME NEXT
  6.  

Pete

Want to learn how to write code on cave walls? https://www.tapatalk.com/groups/qbasic/qbasic-f1/

Offline SMcNeill

  • QB64 Developer
  • Forum Resident
  • Posts: 3972
    • View Profile
    • Steve’s QB64 Archive Forum
Re: ON ERROR and integer division by zero?
« Reply #2 on: December 15, 2018, 12:47:15 pm »
If I remember correctly, QB64 used to internally catch division by zero issues and toss error messages.  At some point, that was changed to produce results more consistent with C-behavior, without any internal error catching.

PRINT 1/0 gives INF as a result now.

With no error check actually occurring, there’s nothing for ON ERROR to catch, so 1\0 tosses the critical error at the OS level.

The only solution at this point is for the programmer to error proof their own code.  Two quick solutions pop to mind:

IF y <> 0 THEN z = x \ y ‘don’t do division if y is 0

OR

PRINT INT(1 / 0) ‘use INT value of real division, instead of integer division.
https://github.com/SteveMcNeill/Steve64 — A github collection of all things Steve!