Detect division by zero: Difference between revisions
No edit summary |
Add SmallBASIC |
||
(77 intermediate revisions by 37 users not shown) | |||
Line 1: | Line 1: | ||
{{task}} |
{{task}} |
||
[[Category:Simple]] |
[[Category:Simple]] |
||
{{omit from|6502 Assembly|6502 has no hardware division so this task is impossible.}} |
|||
{{omit from|8080 Assembly|Z80 has no hardware division so this task is impossible.}} |
|||
{{omit from|Z80 Assembly|Z80 has no hardware division so this task is impossible.}} |
|||
{{omit from|Computer/zero Assembly|no hardware division so this task is impossible.}} |
|||
;Task: |
;Task: |
||
Write a function to detect a ''divide by zero error'' without checking if the denominator is zero. |
Write a function to detect a ''divide by zero error'' without checking if the denominator is zero. |
||
<br><br> |
<br><br> |
||
=={{header|68000 Assembly}}== |
|||
The <code>DIVU</code> and <code>DIVS</code> opcodes will automatically trigger a system call to Trap #5 if division by zero occurs. |
|||
=={{header|8th}}== |
=={{header|8th}}== |
||
Division by zero results in the value "Inf": |
Division by zero results in the value "Inf": |
||
<syntaxhighlight lang="forth"> |
|||
<lang Forth> |
|||
1 0 n:/ Inf? . cr |
1 0 n:/ Inf? . cr |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}}<pre>true</pre> |
{{out}}<pre>true</pre> |
||
=={{header|ABAP}}== |
=={{header|ABAP}}== |
||
< |
<syntaxhighlight lang="abap">report zdiv_zero |
||
data x type i. |
data x type i. |
||
try. |
try. |
||
Line 20: | Line 26: | ||
write 'Divide by zero.'. |
write 'Divide by zero.'. |
||
endtry. |
endtry. |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
< |
<syntaxhighlight lang="ada">-- Divide By Zero Detection |
||
with Ada.Text_Io; use Ada.Text_Io; |
with Ada.Text_Io; use Ada.Text_Io; |
||
Line 54: | Line 60: | ||
end if; |
end if; |
||
New_Line; |
New_Line; |
||
end Divide_By_Zero;</ |
end Divide_By_Zero;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 62: | Line 68: | ||
=={{header|Aime}}== |
=={{header|Aime}}== |
||
< |
<syntaxhighlight lang="aime">integer |
||
divide(integer n, integer d) |
divide(integer n, integer d) |
||
{ |
{ |
||
Line 82: | Line 88: | ||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 110: | Line 116: | ||
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}} |
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}} |
||
< |
<syntaxhighlight lang="algol68">PROC raise exception= ([]STRING args)VOID: ( |
||
put(stand error, ("Exception: ",args, newline)); |
put(stand error, ("Exception: ",args, newline)); |
||
stop |
stop |
||
Line 135: | Line 141: | ||
raise zero division error := a different handler; |
raise zero division error := a different handler; |
||
print(x/y) |
print(x/y) |
||
END</ |
END</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 145: | Line 151: | ||
<br> |
<br> |
||
A count of the number of times the exception is allowed is decremented each time the exception occurs. If this reaches 0, the program crashes. If it is greater than 0, the program continues and XCPNOTED(exception) returns true. This example uses this to detect integer and real division by 0. The INTDIVERO exception also occurs if the remainder (modulo) operator is used with 0. |
A count of the number of times the exception is allowed is decremented each time the exception occurs. If this reaches 0, the program crashes. If it is greater than 0, the program continues and XCPNOTED(exception) returns true. This example uses this to detect integer and real division by 0. The INTDIVERO exception also occurs if the remainder (modulo) operator is used with 0. |
||
< |
<syntaxhighlight lang="algolw">begin |
||
% integer division procedure % |
% integer division procedure % |
||
% sets c to a divided by b, returns true if the division was OK, % |
% sets c to a divided by b, returns true if the division was OK, % |
||
Line 172: | Line 178: | ||
write( divideR( 4, 2, d ) ); % prints false as no exception % |
write( divideR( 4, 2, d ) ); % prints false as no exception % |
||
write( divideR( 5, 0, d ) ) % prints true as division by zero was detected % |
write( divideR( 5, 0, d ) ) % prints true as division by zero was detected % |
||
end.</ |
end.</syntaxhighlight> |
||
=={{header|Arturo}}== |
|||
<syntaxhighlight lang="rebol">try? -> 3/0 |
|||
else -> print "division by zero" </syntaxhighlight> |
|||
{{out}} |
|||
<pre>division by zero</pre> |
|||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
< |
<syntaxhighlight lang="autohotkey">ZeroDiv(num1, num2) { |
||
If ((num1/num2) != "") |
If ((num1/num2) != "") |
||
MsgBox % num1/num2 |
MsgBox % num1/num2 |
||
Line 182: | Line 197: | ||
} |
} |
||
ZeroDiv(0, 3) ; is ok |
ZeroDiv(0, 3) ; is ok |
||
ZeroDiv(3, 0) ; divize by zero alert</ |
ZeroDiv(3, 0) ; divize by zero alert</syntaxhighlight> |
||
=={{header|BASIC}}== |
=={{header|BASIC}}== |
||
Line 188: | Line 203: | ||
==={{header|Applesoft BASIC}}=== |
==={{header|Applesoft BASIC}}=== |
||
The error code for division by zero is 133. There is a good overview of Applesoft ONERR GOTO handling here: |
The error code for division by zero is 133. There is a good overview of Applesoft ONERR GOTO handling here: |
||
http://newsgroups.derkeiler.com/Archive/Comp/comp.sys.apple2.programmer/2010-04/msg00000.html |
https://web.archive.org/web/20190202133738/http://newsgroups.derkeiler.com/Archive/Comp/comp.sys.apple2.programmer/2010-04/msg00000.html |
||
< |
<syntaxhighlight lang="basic"> 100 REM TRY |
||
110 ONERR GOTO 200 |
110 ONERR GOTO 200 |
||
120 D = - 44 / 0 |
120 D = - 44 / 0 |
||
Line 200: | Line 215: | ||
240 CALL - 3288: REM RECOVER |
240 CALL - 3288: REM RECOVER |
||
250 PRINT "DIVISION BY ZERO" |
250 PRINT "DIVISION BY ZERO" |
||
</syntaxhighlight> |
|||
</lang> |
|||
==={{header|BASIC256}}=== |
|||
<syntaxhighlight lang="freebasic">onerror TratoError |
|||
print 2 / 3 |
|||
print 3 / 5 |
|||
print 4 / 0 |
|||
end |
|||
TratoError: |
|||
print "Error in the line " + lasterrorline + " – Error number: " + lasterror + " – " + lasterrormessage + " (" + lasterrorextra + ")" |
|||
return</syntaxhighlight> |
|||
==={{header|BBC BASIC}}=== |
==={{header|BBC BASIC}}=== |
||
< |
<syntaxhighlight lang="bbcbasic"> PROCdivide(-44, 0) |
||
PROCdivide(-44, 5) |
PROCdivide(-44, 5) |
||
PROCdivide(0, 5) |
PROCdivide(0, 5) |
||
Line 221: | Line 248: | ||
ENDCASE |
ENDCASE |
||
ENDIF |
ENDIF |
||
ENDPROC</ |
ENDPROC</syntaxhighlight> |
||
==={{header| |
==={{header|GW-BASIC}}=== |
||
The [[#Locomotive_BASIC|Locomotive BASIC]] solution works without any changes. |
|||
<lang lb>result = DetectDividebyZero(1, 0) |
|||
==={{header|IS-BASIC}}=== |
|||
<syntaxhighlight lang="is-basic">100 WHEN EXCEPTION USE ERROR |
|||
110 FOR I=5 TO-2 STEP-1 |
|||
120 PRINT 10/I |
|||
130 NEXT |
|||
140 END WHEN |
|||
150 HANDLER ERROR |
|||
160 IF EXTYPE=3001 THEN PRINT EXSTRING$(EXTYPE);" in line";EXLINE |
|||
170 CONTINUE |
|||
180 END HANDLER</syntaxhighlight> |
|||
==={{header|Liberty BASIC}}=== |
|||
<syntaxhighlight lang="lb">result = DetectDividebyZero(1, 0) |
|||
Function DetectDividebyZero(a, b) |
Function DetectDividebyZero(a, b) |
||
Line 235: | Line 275: | ||
Notice "Divide by Zero Detected!" |
Notice "Divide by Zero Detected!" |
||
End If |
End If |
||
End Function</ |
End Function</syntaxhighlight> |
||
==={{header|Locomotive Basic}}=== |
==={{header|Locomotive Basic}}=== |
||
< |
<syntaxhighlight lang="locobasic">10 ON ERROR GOTO 60 |
||
20 PRINT 2/3 |
20 PRINT 2/3 |
||
30 PRINT 3/5 |
30 PRINT 3/5 |
||
40 PRINT 4/0 |
40 PRINT 4/0 |
||
50 END |
50 END |
||
60 IF ERR=11 THEN PRINT "Division by zero in line"ERL:RESUME 50</ |
60 IF ERR=11 THEN PRINT "Division by zero in line"ERL:RESUME 50</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 250: | Line 290: | ||
Division by zero in line 40 </pre> |
Division by zero in line 40 </pre> |
||
==={{header| |
==={{header|MSX Basic}}=== |
||
The [[#Locomotive_BASIC|Locomotive BASIC]] solution works without any changes. |
|||
==={{header|PureBasic}}=== |
|||
PureBasic can be compiled with the [http://www.purebasic.com/documentation/onerror/index.html OnError] library included which gives a way to track program errors without losing speed, doing so gives support for the following functions; |
PureBasic can be compiled with the [http://www.purebasic.com/documentation/onerror/index.html OnError] library included which gives a way to track program errors without losing speed, doing so gives support for the following functions; |
||
*ErrorAddress() |
*ErrorAddress() |
||
Line 274: | Line 316: | ||
'''With Integers & OnError Library''' |
'''With Integers & OnError Library''' |
||
< |
<syntaxhighlight lang="purebasic">;Set up a Procedure to handle any Error |
||
Procedure MyErrorHandler() |
Procedure MyErrorHandler() |
||
Define txt$="The following error happened."+#CRLF$+ ErrorMessage()+"at line "+Str(ErrorLine()) |
Define txt$="The following error happened."+#CRLF$+ ErrorMessage()+"at line "+Str(ErrorLine()) |
||
Line 286: | Line 328: | ||
Repeat |
Repeat |
||
A=Random(100)/Random(100) |
A=Random(100)/Random(100) |
||
ForEver</ |
ForEver</syntaxhighlight> |
||
[[Image:OnError.png]] |
[[Image:OnError.png]] |
||
'''With Floats, and without OnError library''' |
'''With Floats, and without OnError library''' |
||
< |
<syntaxhighlight lang="purebasic">Define.d a, b |
||
Debug a/b</ |
Debug a/b</syntaxhighlight> |
||
Results in; |
Results in; |
||
<tt>-1.#IND</tt> |
<tt>-1.#IND</tt> |
||
==={{header|QBasic}}=== |
|||
<syntaxhighlight lang="qbasic">ON ERROR GOTO TratoError |
|||
PRINT 2 / 3 |
|||
PRINT 3 / 5 |
|||
PRINT 4 / 0 |
|||
END |
|||
TratoError: |
|||
PRINT "Error"; ERR; "in the line"; ERL |
|||
IF ERR = 11 THEN PRINT "Division by zero in line"; ERL: RESUME NEXT</syntaxhighlight> |
|||
==={{header|Run BASIC}}=== |
==={{header|Run BASIC}}=== |
||
< |
<syntaxhighlight lang="runbasic">on error goto [error] |
||
a = 1 / 0 |
a = 1 / 0 |
||
wait |
wait |
||
Line 303: | Line 356: | ||
[error] ' error 11 is division by zero err number |
[error] ' error 11 is division by zero err number |
||
If err = 11 Then print "Division by Zero" |
If err = 11 Then print "Division by Zero" |
||
wait</ |
wait</syntaxhighlight> |
||
==={{header|SmallBASIC}}=== |
|||
<syntaxhighlight lang="qbasic"> |
|||
try |
|||
a = 1/0 |
|||
catch error |
|||
print error |
|||
a = nil |
|||
end try |
|||
print a |
|||
</syntaxhighlight> |
|||
==={{header|TI-89 BASIC}}=== |
==={{header|TI-89 BASIC}}=== |
||
<code>1/0 = undef</code> is true. |
<code>1/0 = undef</code> is true. |
||
==={{header|True BASIC}}=== |
|||
<syntaxhighlight lang="qbasic">WHEN error in |
|||
PRINT 2 / 3 |
|||
PRINT 3 / 5 |
|||
PRINT 4 / 0 |
|||
USE |
|||
PRINT "Error "; EXTYPE; "in the line"; EXLINE |
|||
PRINT EXTEXT$ |
|||
END WHEN |
|||
END</syntaxhighlight> |
|||
=={{header|Batch File}}== |
=={{header|Batch File}}== |
||
< |
<syntaxhighlight lang="dos">@echo off |
||
set /a dummy=5/0 2>nul |
set /a dummy=5/0 2>nul |
||
if %errorlevel%==1073750993 echo I caught a division by zero operation... |
if %errorlevel%==1073750993 echo I caught a division by zero operation... |
||
exit /b 0</ |
exit /b 0</syntaxhighlight> |
||
=={{header|BQN}}== |
|||
Division of a non-zero number by zero results in infinity, a predefined symbol in BQN. |
|||
In [[CBQN]] and [[mlochbaum/BQN]], 0 divided by 0 results in <code>NaN</code> (not a number), so we can test these two cases to find out a division by zero error, provided the numerator isn't <code>∞</code> or <code>NaN</code> to start with. |
|||
<syntaxhighlight lang="bqn">Div ← {∨´"∞"‿"NaN"≡¨<•Fmt𝕩}◶⊢‿"Division by 0"÷ |
|||
•Show 5 Div 0 |
|||
•Show 5 Div 5 |
|||
•Show 0 Div 0</syntaxhighlight><syntaxhighlight lang="bqn">"Division by 0" |
|||
1 |
|||
"Division by 0"</syntaxhighlight> |
|||
[https://mlochbaum.github.io/BQN/try.html#code=RGl2IOKGkCB74oiowrQi4oieIuKAvyJOYU4i4omhwqg84oCiRm108J2VqX3il7biiqLigL8iRGl2aXNpb24gYnkgMCLDtwoK4oCiU2hvdyA1IERpdiAwCuKAolNob3cgNSBEaXYgNQrigKJTaG93IDAgRGl2IDA= Try It!] |
|||
=={{header|C}}== |
=={{header|C}}== |
||
Technically, under the C standard, division by zero (regardless of type) is undefined behavior, so there is no standard way to run the division and then try to "detect" it later. |
Technically, under the C standard, division by zero (regardless of type) is undefined behavior, so there is no standard way to run the division and then try to "detect" it later. |
||
Line 324: | Line 416: | ||
Some systems will raise SIGFPE if a program divides by zero. |
Some systems will raise SIGFPE if a program divides by zero. |
||
< |
<syntaxhighlight lang="c">#include <limits.h> /* INT_MIN */ |
||
#include <setjmp.h> /* siglongjmp(), sigsetjmp() */ |
#include <setjmp.h> /* siglongjmp(), sigsetjmp() */ |
||
#include <stdio.h> /* perror(), printf() */ |
#include <stdio.h> /* perror(), printf() */ |
||
Line 423: | Line 515: | ||
try_division(INT_MIN, -1); |
try_division(INT_MIN, -1); |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} using OpenBSD/amd64: |
{{out}} using OpenBSD/amd64: |
||
Line 433: | Line 525: | ||
The last line is a mistake: the system confused an overflow (INT_MIN / -1 would be INT_MAX + 1) with division by zero and raised SIGFPE. The system normally ignores overflow. |
The last line is a mistake: the system confused an overflow (INT_MIN / -1 would be INT_MAX + 1) with division by zero and raised SIGFPE. The system normally ignores overflow. |
||
=={{header|C sharp|C#}}== |
|||
{{works with|int, long, decimal}} |
|||
The floating point types (float, double) don't raise an exception, but return the values Infinity or NaN as appropriate. |
|||
<syntaxhighlight lang="csharp">using System; |
|||
namespace RosettaCode { |
|||
class Program { |
|||
static void Main(string[] args) { |
|||
int x = 1; |
|||
int y = 0; |
|||
try { |
|||
int z = x / y; |
|||
} catch (DivideByZeroException e) { |
|||
Console.WriteLine(e); |
|||
} |
|||
} |
|||
} |
|||
}</syntaxhighlight> |
|||
=={{header|C++}}== |
=={{header|C++}}== |
||
< |
<syntaxhighlight lang="cpp"> |
||
#include<iostream> |
#include<iostream> |
||
#include<csignal> /* for signal */ |
#include<csignal> /* for signal */ |
||
Line 459: | Line 572: | ||
return 0; |
return 0; |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|C sharp|C#}}== |
|||
{{works with|int, long, decimal}} |
|||
The floating point types (float, double) don't raise an exception, but return the values Infinity or NaN as appropriate. |
|||
<lang csharp>using System; |
|||
namespace RosettaCode { |
|||
class Program { |
|||
static void Main(string[] args) { |
|||
int x = 1; |
|||
int y = 0; |
|||
try { |
|||
int z = x / y; |
|||
} catch (DivideByZeroException e) { |
|||
Console.WriteLine(e); |
|||
} |
|||
} |
|||
} |
|||
}</lang> |
|||
=={{header|Ceylon}}== |
=={{header|Ceylon}}== |
||
< |
<syntaxhighlight lang="ceylon">shared void run() { |
||
//integers divided by zero throw an exception |
//integers divided by zero throw an exception |
||
Line 494: | Line 586: | ||
//floats divided by zero produce infinity |
//floats divided by zero produce infinity |
||
print(1.0 / 0 == infinity then "division by zero!" else "not division by zero!"); |
print(1.0 / 0 == infinity then "division by zero!" else "not division by zero!"); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
Line 501: | Line 593: | ||
return +inf, if 0, NaN, otherwise -inf. |
return +inf, if 0, NaN, otherwise -inf. |
||
< |
<syntaxhighlight lang="lisp">(defn safe-/ [x y] |
||
(try (/ x y) |
(try (/ x y) |
||
(catch ArithmeticException _ |
(catch ArithmeticException _ |
||
Line 507: | Line 599: | ||
(cond (> x 0) Double/POSITIVE_INFINITY |
(cond (> x 0) Double/POSITIVE_INFINITY |
||
(zero? x) Double/NaN |
(zero? x) Double/NaN |
||
:else Double/NEGATIVE_INFINITY) )))</ |
:else Double/NEGATIVE_INFINITY) )))</syntaxhighlight> |
||
=={{header|CLU}}== |
|||
<syntaxhighlight lang="clu">% This will catch a divide-by-zero exception and |
|||
% return a oneof instead, with either the result or div_by_zero. |
|||
% Overflow and underflow are resignaled. |
|||
check_div = proc [T: type] (a, b: T) returns (otype) |
|||
signals (overflow, underflow) |
|||
where T has div: proctype (T,T) returns (T) |
|||
signals (zero_divide, overflow, underflow) |
|||
otype = oneof[div_by_zero: null, result: T] |
|||
return(otype$make_result(a/b)) |
|||
except when zero_divide: |
|||
return(otype$make_div_by_zero(nil)) |
|||
end resignal overflow, underflow |
|||
end check_div |
|||
% Try it |
|||
start_up = proc () |
|||
pair = struct[n, d: int] |
|||
pairs: sequence[pair] := sequence[pair]$[ |
|||
pair${n: 10, d: 2}, % OK |
|||
pair${n: 10, d: 0}, % divide by zero |
|||
pair${n: 20, d: 2} % another OK one to show the program doesn't stop |
|||
] |
|||
po: stream := stream$primary_output() |
|||
for p: pair in sequence[pair]$elements(pairs) do |
|||
stream$puts(po, int$unparse(p.n) || "/" || int$unparse(p.d) || " = ") |
|||
tagcase check_div[int](p.n, p.d) |
|||
tag div_by_zero: stream$putl(po, "divide by zero") |
|||
tag result (r: int): stream$putl(po, int$unparse(r)) |
|||
end |
|||
end |
|||
end start_up</syntaxhighlight> |
|||
{{out}} |
|||
<pre>10/2 = 5 |
|||
10/0 = divide by zero |
|||
20/2 = 10</pre> |
|||
=={{header|COBOL}}== |
=={{header|COBOL}}== |
||
< |
<syntaxhighlight lang="cobol">DIVIDE foo BY bar GIVING foobar |
||
ON SIZE ERROR |
ON SIZE ERROR |
||
DISPLAY "Division by zero detected!" |
DISPLAY "Division by zero detected!" |
||
END-DIVIDE</ |
END-DIVIDE</syntaxhighlight> |
||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
< |
<syntaxhighlight lang="lisp">(handler-case (/ x y) |
||
(division-by-zero () (format t "division by zero caught!~%")))</ |
(division-by-zero () (format t "division by zero caught!~%")))</syntaxhighlight> |
||
=={{header|D}}== |
=={{header|D}}== |
||
< |
<syntaxhighlight lang="d">import std.stdio, std.string, std.math, std.traits; |
||
string divCheck(T)(in T numer, in T denom) |
string divCheck(T)(in T numer, in T denom) |
||
Line 573: | Line 704: | ||
divCheck(real.infinity, real.infinity)); |
divCheck(real.infinity, real.infinity)); |
||
writefln("real nan/ nan: %s", divCheck(real.nan, real.nan)); |
writefln("real nan/ nan: %s", divCheck(real.nan, real.nan)); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Division with check: |
<pre>Division with check: |
||
Line 592: | Line 723: | ||
real inf/ inf: -nan | Inf numerator |
real inf/ inf: -nan | Inf numerator |
||
real nan/ nan: nan | NaN numerator</pre> |
real nan/ nan: nan | NaN numerator</pre> |
||
=={{header|Déjà Vu}}== |
|||
<lang dejavu>divcheck x y: |
|||
true |
|||
try: |
|||
drop / x y |
|||
catch value-error: |
|||
not |
|||
if divcheck 1 0: |
|||
!print "Okay" |
|||
else: |
|||
!print "Division by zero"</lang> |
|||
{{out}} |
|||
<pre>Division by zero</pre> |
|||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
< |
<syntaxhighlight lang="delphi">program DivideByZero; |
||
{$APPTYPE CONSOLE} |
{$APPTYPE CONSOLE} |
||
Line 626: | Line 742: | ||
Writeln(e.Message); |
Writeln(e.Message); |
||
end; |
end; |
||
end.</ |
end.</syntaxhighlight> |
||
=={{header|Déjà Vu}}== |
|||
<syntaxhighlight lang="dejavu">divcheck x y: |
|||
true |
|||
try: |
|||
drop / x y |
|||
catch value-error: |
|||
not |
|||
if divcheck 1 0: |
|||
!print "Okay" |
|||
else: |
|||
!print "Division by zero"</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Division by zero</pre> |
|||
=={{header|E}}== |
=={{header|E}}== |
||
< |
<syntaxhighlight lang="e">def divide(numerator, denominator) { |
||
def floatQuotient := numerator / denominator |
def floatQuotient := numerator / denominator |
||
if (floatQuotient.isNaN() || floatQuotient.isInfinite()) { |
if (floatQuotient.isNaN() || floatQuotient.isInfinite()) { |
||
Line 637: | Line 768: | ||
return ["ok", floatQuotient] |
return ["ok", floatQuotient] |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|EasyLang}}== |
|||
<syntaxhighlight lang="easylang"> |
|||
func checkDivZero a b . |
|||
r = a / b |
|||
if r = number "nan" or r = number "inf" or r = number "-inf" |
|||
return 1 |
|||
. |
|||
. |
|||
print checkDivZero 5 7 |
|||
print checkDivZero -1 0 |
|||
</syntaxhighlight> |
|||
=={{header|ECL}}== |
=={{header|ECL}}== |
||
Line 643: | Line 786: | ||
Evaluate to zero - default behavior |
Evaluate to zero - default behavior |
||
<syntaxhighlight lang="ecl"> |
|||
<lang ECL> |
|||
DBZ(REAL8 Dividend,INTEGER8 Divisor) := Quotient/Divisor; |
DBZ(REAL8 Dividend,INTEGER8 Divisor) := Quotient/Divisor; |
||
#option ('divideByZero', 'zero'); |
#option ('divideByZero', 'zero'); |
||
DBZ(10,0); //returns 0.0 |
DBZ(10,0); //returns 0.0 |
||
</syntaxhighlight> |
|||
</lang> |
|||
Stop and report a division by zero error: |
Stop and report a division by zero error: |
||
<syntaxhighlight lang="ecl"> |
|||
<lang ECL> |
|||
DBZ(REAL8 Dividend,INTEGER8 Divisor) := Quotient/Divisor; |
DBZ(REAL8 Dividend,INTEGER8 Divisor) := Quotient/Divisor; |
||
#option ('divideByZero', 'fail'); |
#option ('divideByZero', 'fail'); |
||
DBZ(10,0); //returns error message "Error: System error: -1: Division by zero (0, 0), -1," |
DBZ(10,0); //returns error message "Error: System error: -1: Division by zero (0, 0), -1," |
||
</syntaxhighlight> |
|||
</lang> |
|||
Returns "nan": |
Returns "nan": |
||
<syntaxhighlight lang="ecl"> |
|||
<lang ECL> |
|||
DBZ(REAL8 Dividend,INTEGER8 Divisor) := Quotient/Divisor; |
DBZ(REAL8 Dividend,INTEGER8 Divisor) := Quotient/Divisor; |
||
#option ('divideByZero', 'nan'); |
#option ('divideByZero', 'nan'); |
||
Line 666: | Line 809: | ||
Integer and decimal division by zero continue to return 0. |
Integer and decimal division by zero continue to return 0. |
||
*/ |
*/ |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Eiffel}}== |
=={{header|Eiffel}}== |
||
Line 672: | Line 815: | ||
In a file called main.e: |
In a file called main.e: |
||
< |
<syntaxhighlight lang="eiffel">class MAIN |
||
creation main |
creation main |
||
feature main is |
feature main is |
||
Line 692: | Line 835: | ||
retry |
retry |
||
end |
end |
||
end</ |
end</syntaxhighlight> |
||
Note: The "rescue" statement catches ''every'' exception. |
Note: The "rescue" statement catches ''every'' exception. |
||
=={{header|Ela}}== |
=={{header|Ela}}== |
||
< |
<syntaxhighlight lang="ela">open core number |
||
x /. y = try Some (x `div` y) with |
x /. y = try Some (x `div` y) with |
||
_ = None |
_ = None |
||
(12 /. 2, 12 /. 0)</ |
(12 /. 2, 12 /. 0)</syntaxhighlight> |
||
Output: |
Output: |
||
Line 710: | Line 853: | ||
Of course the cleanest way to implement the safe division function is through pattern matching: |
Of course the cleanest way to implement the safe division function is through pattern matching: |
||
< |
<syntaxhighlight lang="ela">x /. 0 = None |
||
x /. y = Some (x / y)</ |
x /. y = Some (x / y)</syntaxhighlight> |
||
But it doesn't satisfy the task. |
But it doesn't satisfy the task. |
||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
< |
<syntaxhighlight lang="elixir">defmodule Division do |
||
def by_zero?(x,y) do |
def by_zero?(x,y) do |
||
try do |
try do |
||
Line 730: | Line 873: | ||
|> Enum.each(fn {x,y} -> |
|> Enum.each(fn {x,y} -> |
||
IO.puts "#{x} / #{y}\tdivision by zero #{Division.by_zero?(x,y)}" |
IO.puts "#{x} / #{y}\tdivision by zero #{Division.by_zero?(x,y)}" |
||
end)</ |
end)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 747: | Line 890: | ||
Division by zero gives an error of type <code>arith-error</code> which can be caught in the usual ways with <code>condition-case</code> and similar. A division by zero example can be found in the Elisp manual section [http://www.gnu.org/s/emacs/manual/html_node/elisp/Handling-Errors.html "Handling Errors"]. |
Division by zero gives an error of type <code>arith-error</code> which can be caught in the usual ways with <code>condition-case</code> and similar. A division by zero example can be found in the Elisp manual section [http://www.gnu.org/s/emacs/manual/html_node/elisp/Handling-Errors.html "Handling Errors"]. |
||
< |
<syntaxhighlight lang="lisp">(condition-case nil |
||
(/ 1 0) |
(/ 1 0) |
||
(arith-error |
(arith-error |
||
(message "Divide by zero (either integer or float)")))</ |
(message "Divide by zero (either integer or float)")))</syntaxhighlight> |
||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
< |
<syntaxhighlight lang="erlang">div_check(X,Y) -> |
||
case catch X/Y of |
case catch X/Y of |
||
{'EXIT',_} -> true; |
{'EXIT',_} -> true; |
||
_ -> false |
_ -> false |
||
end.</ |
end.</syntaxhighlight> |
||
=={{header|ERRE}}== |
=={{header|ERRE}}== |
||
<syntaxhighlight lang="erre"> |
|||
<lang ERRE> |
|||
PROGRAM DIV_BY_ZERO |
PROGRAM DIV_BY_ZERO |
||
Line 771: | Line 914: | ||
PRINT(3/0) |
PRINT(3/0) |
||
END PROGRAM |
END PROGRAM |
||
</syntaxhighlight> |
|||
</lang> |
|||
EXCEPTION (when it's present) detects runtime errors, otherwise program stops with a |
EXCEPTION (when it's present) detects runtime errors, otherwise program stops with a |
||
[Runtime error #nn] where nn is the error code. Error codes are different between C-64 and PC version. |
[Runtime error #nn] where nn is the error code. Error codes are different between C-64 and PC version. |
||
Line 781: | Line 924: | ||
=={{header|F_Sharp|F#}}== |
=={{header|F_Sharp|F#}}== |
||
< |
<syntaxhighlight lang="fsharp">let detectDivideZero (x : int) (y : int):int option = |
||
try |
try |
||
Some(x / y) |
Some(x / y) |
||
Line 789: | Line 932: | ||
printfn "12 divided by 3 is %A" (detectDivideZero 12 3) |
printfn "12 divided by 3 is %A" (detectDivideZero 12 3) |
||
printfn "1 divided by 0 is %A" (detectDivideZero 1 0)</ |
printfn "1 divided by 0 is %A" (detectDivideZero 1 0)</syntaxhighlight> |
||
Output: |
Output: |
||
Line 796: | Line 939: | ||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
< |
<syntaxhighlight lang="factor">USE: math.floats.env |
||
: try-div ( a b -- ) |
: try-div ( a b -- ) |
||
'[ { +fp-zero-divide+ } [ _ _ /f . ] with-fp-traps ] try ;</ |
'[ { +fp-zero-divide+ } [ _ _ /f . ] with-fp-traps ] try ;</syntaxhighlight> |
||
( scratchpad ) 1 2 try-div |
( scratchpad ) 1 2 try-div |
||
Line 809: | Line 952: | ||
=={{header|Fancy}}== |
=={{header|Fancy}}== |
||
< |
<syntaxhighlight lang="fancy">def divide: x by: y { |
||
try { |
try { |
||
x / y |
x / y |
||
Line 816: | Line 959: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
< |
<syntaxhighlight lang="forth">: safe-/ ( x y -- x/y ) |
||
['] / catch -55 = if cr ." divide by zero!" 2drop 0 then ;</ |
['] / catch -55 = if cr ." divide by zero!" 2drop 0 then ;</syntaxhighlight> |
||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
Line 827: | Line 970: | ||
Floating-point division by zero detection. |
Floating-point division by zero detection. |
||
< |
<syntaxhighlight lang="fortran"> |
||
program rosetta_divbyzero |
program rosetta_divbyzero |
||
implicit none |
implicit none |
||
Line 869: | Line 1,012: | ||
end program rosetta_divbyzero |
end program rosetta_divbyzero |
||
</syntaxhighlight> |
|||
</lang> |
|||
Integer division by zero. No detection. |
Integer division by zero. No detection. |
||
< |
<syntaxhighlight lang="fortran"> |
||
program rosetta_integer_divbyzero |
program rosetta_integer_divbyzero |
||
implicit none |
implicit none |
||
Line 882: | Line 1,025: | ||
write(*,*) answer |
write(*,*) answer |
||
end program rosetta_integer_divbyzero |
end program rosetta_integer_divbyzero |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
Line 893: | Line 1,036: | ||
The following code relies on this 'hack':- |
The following code relies on this 'hack':- |
||
< |
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64 |
||
Const divByZeroResult As Integer = -9223372036854775808 |
Const divByZeroResult As Integer = -9223372036854775808 |
||
Line 917: | Line 1,060: | ||
Print |
Print |
||
Print "Press any key to exit" |
Print "Press any key to exit" |
||
Sleep</ |
Sleep</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 929: | Line 1,072: | ||
=={{header|FutureBasic}}== |
=={{header|FutureBasic}}== |
||
Stop on error. Error type reported in log console. |
Stop on error. Error type reported in log console. |
||
< |
<syntaxhighlight lang="futurebasic"> |
||
include "ConsoleWindow" |
|||
on error stop |
on error stop |
||
long a |
|||
print a / 0 |
print a / 0 |
||
</lang> |
|||
HandleEvents |
|||
</syntaxhighlight> |
|||
=={{header|Gambas}}== |
=={{header|Gambas}}== |
||
'''[https://gambas-playground.proko.eu/?gist=6c837b97d9c5f296ef23245706544bdf Click this link to run this code]''' |
'''[https://gambas-playground.proko.eu/?gist=6c837b97d9c5f296ef23245706544bdf Click this link to run this code]''' |
||
< |
<syntaxhighlight lang="gambas">Public Sub Main() |
||
Try Print 1 / 0 |
Try Print 1 / 0 |
||
If Error Then Print Error.Text |
If Error Then Print Error.Text |
||
End</ |
End</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 952: | Line 1,095: | ||
=={{header|Go}}== |
=={{header|Go}}== |
||
Detection on integers by recovering from a panic: |
Detection on integers by recovering from a panic: |
||
< |
<syntaxhighlight lang="go">package main |
||
import "fmt" |
import "fmt" |
||
Line 967: | Line 1,110: | ||
fmt.Println(divCheck(3, 2)) |
fmt.Println(divCheck(3, 2)) |
||
fmt.Println(divCheck(3, 0)) |
fmt.Println(divCheck(3, 0)) |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 976: | Line 1,119: | ||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
In Groovy, the float and double types follow IEEE numeric formats and rules. Here is a solution for double: |
In Groovy, the float and double types follow IEEE numeric formats and rules. Here is a solution for double: |
||
< |
<syntaxhighlight lang="groovy">def dividesByZero = { double n, double d -> |
||
assert ! n.infinite : 'Algorithm fails if the numerator is already infinite.' |
assert ! n.infinite : 'Algorithm fails if the numerator is already infinite.' |
||
(n/d).infinite || (n/d).naN |
(n/d).infinite || (n/d).naN |
||
}</ |
}</syntaxhighlight> |
||
Test program: |
Test program: |
||
< |
<syntaxhighlight lang="groovy">((3d)..(0d)).each { i -> |
||
((2d)..(0d)).each { j -> |
((2d)..(0d)).each { j -> |
||
println "${i}/${j} divides by zero? " + dividesByZero(i,j) |
println "${i}/${j} divides by zero? " + dividesByZero(i,j) |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
Line 1,003: | Line 1,146: | ||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
< |
<syntaxhighlight lang="haskell">import qualified Control.Exception as C |
||
check x y = C.catch (x `div` y `seq` return False) |
check x y = C.catch (x `div` y `seq` return False) |
||
(\_ -> return True)</ |
(\_ -> return True)</syntaxhighlight> |
||
=={{header|hexiscript}}== |
|||
<syntaxhighlight lang="hexiscript">let a 1 |
|||
let b 0 |
|||
if tostr (a / (b + 0.)) = "inf" |
|||
println "Divide by Zero" |
|||
else |
|||
println a / b |
|||
endif</syntaxhighlight> |
|||
=={{header|HicEst}}== |
=={{header|HicEst}}== |
||
< |
<syntaxhighlight lang="hicest">FUNCTION zero_divide(num, denom) |
||
XEQ( num// "/" // denom, *99) ! on error jump to label 99 |
XEQ( num// "/" // denom, *99) ! on error jump to label 99 |
||
zero_divide = 0 ! division OK |
zero_divide = 0 ! division OK |
||
Line 1,014: | Line 1,166: | ||
99 zero_divide = 1 |
99 zero_divide = 1 |
||
END</ |
END</syntaxhighlight> |
||
< |
<syntaxhighlight lang="hicest">zero_divide(0, 1) returns 0 (false) |
||
zero_divide( 1, 3-2-1 ) returns 1 (true)</ |
zero_divide( 1, 3-2-1 ) returns 1 (true)</syntaxhighlight> |
||
=={{header|HolyC}}== |
=={{header|HolyC}}== |
||
HolyC throws <code>Except:DivZero</code>. |
HolyC throws <code>Except:DivZero</code>. |
||
< |
<syntaxhighlight lang="holyc">try { |
||
Print("%d\n", 10 / 0); |
Print("%d\n", 10 / 0); |
||
} catch { |
} catch { |
||
Print("Divide by zero"); |
Print("Divide by zero"); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|i}}== |
=={{header|i}}== |
||
< |
<syntaxhighlight lang="i">//Division by zero is defined in 'i' so the result can be checked to determine division by zero. |
||
concept IsDivisionByZero(a, b) { |
concept IsDivisionByZero(a, b) { |
||
c = a/b |
c = a/b |
||
Line 1,041: | Line 1,193: | ||
IsDivisionByZero(5, 2) |
IsDivisionByZero(5, 2) |
||
IsDivisionByZero(0, 0) |
IsDivisionByZero(0, 0) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|IDL}}== |
|||
<lang idl>if not finite( <i>expression</i> ) then ...</lang> |
|||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
Setting &error to a non-zero number traps errors and converts then to failures. Division by zero generates error 201 |
Setting &error to a non-zero number traps errors and converts then to failures. Division by zero generates error 201 |
||
< |
<syntaxhighlight lang="icon">procedure main() |
||
&error := 1 |
&error := 1 |
||
udef := 1 / 0 | stop("Run-time error ", &errornumber, " : ", &errortext," in line #",&line," - converted to failure") |
udef := 1 / 0 | stop("Run-time error ", &errornumber, " : ", &errortext," in line #",&line," - converted to failure") |
||
end</ |
end</syntaxhighlight> |
||
Sample Output:<pre>Run-time error 201 : division by zero in line #3 - converted to failure</pre> |
Sample Output:<pre>Run-time error 201 : division by zero in line #3 - converted to failure</pre> |
||
=={{header|IDL}}== |
|||
<syntaxhighlight lang="idl">if not finite( <i>expression</i> ) then ...</syntaxhighlight> |
|||
=={{header|J}}== |
=={{header|J}}== |
||
Line 1,065: | Line 1,217: | ||
So, anyways, the task: |
So, anyways, the task: |
||
< |
<syntaxhighlight lang="j">funnydiv=: 0 { [: (,:'division by zero detected')"_^:(_ e. |@,) (,>:)@:(,:^:(0<#@$))@[ %"_1 _ ]</syntaxhighlight> |
||
This performs division and instead of returning the result returns the string 'division by zero detected' if a denominator was zero. Note that it also provides this result if a numerator was infinite, regardless of the denominator, but since there's no reasonable use for this implementation that's probably not a problem. |
This performs division and instead of returning the result returns the string 'division by zero detected' if a denominator was zero. Note that it also provides this result if a numerator was infinite, regardless of the denominator, but since there's no reasonable use for this implementation that's probably not a problem. |
||
Line 1,071: | Line 1,223: | ||
Examples: |
Examples: |
||
< |
<syntaxhighlight lang="j"> 3 funnydiv 2 |
||
1.5 |
1.5 |
||
3 funnydiv 0 |
3 funnydiv 0 |
||
Line 1,080: | Line 1,232: | ||
0 |
0 |
||
2 3 4 funnydiv 5 |
2 3 4 funnydiv 5 |
||
0.4 0.6 0.8</ |
0.4 0.6 0.8</syntaxhighlight> |
||
=={{header|Java}}== |
=={{header|Java}}== |
||
Line 1,086: | Line 1,238: | ||
One way to do this check in Java is to use the <tt>isInfinite</tt> function from the <tt>Double</tt> class: |
One way to do this check in Java is to use the <tt>isInfinite</tt> function from the <tt>Double</tt> class: |
||
< |
<syntaxhighlight lang="java">public static boolean infinity(double numer, double denom){ |
||
return Double.isInfinite(numer/denom); |
return Double.isInfinite(numer/denom); |
||
}</ |
}</syntaxhighlight> |
||
Another way is to use the <tt>ArithmeticException</tt> as a check (which is not preferred because it expects an exception): |
Another way is to use the <tt>ArithmeticException</tt> as a check (which is not preferred because it expects an exception): |
||
< |
<syntaxhighlight lang="java">public static boolean except(double numer, double denom){ |
||
try{ |
try{ |
||
int dummy = (int)numer / (int)denom;//ArithmeticException is only thrown from integer math |
int dummy = (int)numer / (int)denom;//ArithmeticException is only thrown from integer math |
||
return false; |
return false; |
||
}catch(ArithmeticException e){return true;} |
}catch(ArithmeticException e){return true;} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
JavaScript does not give an error on division by 0, and this is more useful than it is Mathematically correct. However, 0 divided by 0 will yield NaN, which is actually correct, since 0/0 is defined as "indeterminate". It may be better to return 0 or false in these situations, though, depending on the application (in JavaScript, 0 and false are the same thing): |
JavaScript does not give an error on division by 0, and this is more useful than it is Mathematically correct. However, 0 divided by 0 will yield NaN, which is actually correct, since 0/0 is defined as "indeterminate". It may be better to return 0 or false in these situations, though, depending on the application (in JavaScript, 0 and false are the same thing): |
||
< |
<syntaxhighlight lang="javascript">function divByZero(dividend,divisor) |
||
{ |
{ |
||
var quotient=dividend/divisor; |
var quotient=dividend/divisor; |
||
Line 1,105: | Line 1,257: | ||
return quotient; //Will return Infinity or -Infinity in cases of, for example, 5/0 or -7/0 respectively |
return quotient; //Will return Infinity or -Infinity in cases of, for example, 5/0 or -7/0 respectively |
||
} |
} |
||
alert(divByZero(0,0));</ |
alert(divByZero(0,0));</syntaxhighlight> |
||
This will output "0" instead of "NaN". In this case, when checking against for true, the condition needs to be explicit ("===" rather than "==") because if divByZero(5,5) is used, this will return 1, which is the same as true when using "==". |
This will output "0" instead of "NaN". In this case, when checking against for true, the condition needs to be explicit ("===" rather than "==") because if divByZero(5,5) is used, this will return 1, which is the same as true when using "==". |
||
Line 1,112: | Line 1,264: | ||
We can however define div(x;y) so that it raises an error, "NaN", if y equals 0: |
We can however define div(x;y) so that it raises an error, "NaN", if y equals 0: |
||
< |
<syntaxhighlight lang="jq">def div(x;y): if y==0 then error("NaN") else x/y end;</syntaxhighlight> |
||
In versions of jq since 1.4, we can then catch the error, as illustrated by the following snippet:< |
In versions of jq since 1.4, we can then catch the error, as illustrated by the following snippet:<syntaxhighlight lang="jq"> |
||
try div(3;0) catch if "NaN" then "div by 0 error detected" else . end</ |
try div(3;0) catch if "NaN" then "div by 0 error detected" else . end</syntaxhighlight> |
||
=={{header| |
=={{header|Jsish}}== |
||
Like other ECMAScript implementations, Jsi does not error out on divide by zero. There is the internal representation of +Infinity, -Infinity and NaN. Detection of division by zero is not exact, other problems with the arithmetic can also set the state, but: |
|||
{{works with|Julia|0.6}} |
|||
<syntaxhighlight lang="javascript">if (!isFinite(numerator/denominator)) puts("result is infinity or not a number");</syntaxhighlight> |
|||
=={{header|Julia}}== |
|||
Julia handles division by zero quite gracefully. The result depends upon the numerator: <code>Inf</code>, <code>-Inf</code>, <code>NaN</code> or (for complex numbers) some mixture of these. This solution detects division by zero by checking for these sorts of values. |
Julia handles division by zero quite gracefully. The result depends upon the numerator: <code>Inf</code>, <code>-Inf</code>, <code>NaN</code> or (for complex numbers) some mixture of these. This solution detects division by zero by checking for these sorts of values. |
||
< |
<syntaxhighlight lang="julia">isdefinite(n::Number) = !isnan(n) && !isinf(n) |
||
for n in (1, 1//1, 1.0, 1im, 0) |
for n in (1, 1//1, 1.0, 1im, 0) |
||
d = n / 0 |
d = n / 0 |
||
println("Dividing $n by 0 ", isdefinite(d) ? "results in $d." : "yields an indefinite value ($d).") |
println("Dividing $n by 0 ", isdefinite(d) ? "results in $d." : "yields an indefinite value ($d).") |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,135: | Line 1,290: | ||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
< |
<syntaxhighlight lang="scala">// version 1.1 |
||
fun divideByZero(x: Int, y:Int): Boolean = |
fun divideByZero(x: Int, y:Int): Boolean = |
||
Line 1,154: | Line 1,309: | ||
println("$x / $y = ${x / y}") |
println("$x / $y = ${x / y}") |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,160: | Line 1,315: | ||
Attempted to divide by zero |
Attempted to divide by zero |
||
</pre> |
</pre> |
||
=={{header|Lambdatalk}}== |
|||
Thanks to Javascript a division by zero doesn't throw an error, just the word "Infinity". |
|||
<syntaxhighlight lang="scheme"> |
|||
{def DivByZero? |
|||
{lambda {:w} |
|||
{W.equal? :w Infinity}}} |
|||
{DivByZero? {/ 3 2}} |
|||
-> false |
|||
{DivByZero? {/ 3 0}} |
|||
-> true |
|||
</syntaxhighlight> |
|||
=={{header|LabVIEW}}== |
=={{header|LabVIEW}}== |
||
Line 1,165: | Line 1,334: | ||
If the division node receives zero on both nodes (0/0), the Result will be "NaN" |
If the division node receives zero on both nodes (0/0), the Result will be "NaN" |
||
=={{header|langur}}== |
|||
<syntaxhighlight lang="langur"> |
|||
val dz = fn(x, y) { |
|||
[x / y, true] |
|||
catch { |
|||
if _err'msg -> re/division by 0/ { |
|||
[0, false] |
|||
} else { |
|||
# rethrow the error if not division by 0 |
|||
throw |
|||
} |
|||
} |
|||
} |
|||
writeln dz(3, 2) |
|||
writeln dz(3, 0) |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre>[1.5, true] |
|||
[0, false] |
|||
</pre> |
|||
=={{header|Lasso}}== |
=={{header|Lasso}}== |
||
< |
<syntaxhighlight lang="lasso">define dividehandler(a,b) => { |
||
( |
( |
||
#a->isNotA(::integer) && #a->isNotA(::decimal) || |
#a->isNotA(::integer) && #a->isNotA(::decimal) || |
||
Line 1,179: | Line 1,371: | ||
} |
} |
||
dividehandler(1,0)</ |
dividehandler(1,0)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,185: | Line 1,377: | ||
=={{header|Lingo}}== |
=={{header|Lingo}}== |
||
< |
<syntaxhighlight lang="lingo">on div (a, b) |
||
-- for simplicity type check of vars omitted |
-- for simplicity type check of vars omitted |
||
res = value("float(a)/b") |
res = value("float(a)/b") |
||
Line 1,193: | Line 1,385: | ||
return res |
return res |
||
end if |
end if |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
Lua, like Javascript, does not error on DIVIDE-BY-ZERO, but returns infinity. So: |
Lua, like Javascript, does not error on DIVIDE-BY-ZERO, but returns infinity, -infinity or -nan. So: |
||
< |
<syntaxhighlight lang="lua">local function div(a,b) |
||
if b == 0 then error() end |
|||
quot = a/b |
|||
return a/b |
|||
if quot == 1/0 then error() end |
|||
end</syntaxhighlight> |
|||
return quot |
|||
end</lang> |
|||
=={{header|M2000 Interpreter}}== |
|||
To place a division as argument for lazy evaluation we have to use lazy$() which make a proper anonymous function. So we get a() as a function in DetectDivisionByZero() and try to execute. So if we get the specific error we get true. |
|||
Lazy$() not only make a function but also pass the same scope to that function where we use it. So Variables A, B, Z which they are in scope in module Checkit, and not in Function DetectDivisionByZero(), they used by the lazy evaluation contraction. References in M2000 passed as weak references, and for functions passed as code in a string (for objects passed the weak reference of the object plus the code). |
|||
<syntaxhighlight lang="m2000 interpreter"> |
|||
Print function("{Read x : =x**2}", 2)=4 |
|||
</syntaxhighlight> |
|||
For a fast way to check a valid expression we can use Valid() |
|||
<syntaxhighlight lang="m2000 interpreter"> |
|||
Print Valid(100/0)=False |
|||
</syntaxhighlight> |
|||
<syntaxhighlight lang="m2000 interpreter"> |
|||
Module Checkit { |
|||
Function DetectDivisionByZero(&a()) { |
|||
Try { |
|||
a=a() |
|||
} |
|||
=Error$=" division by zero" |
|||
} |
|||
Print DetectDivisionByZero(lazy$(10/0))=True |
|||
Z=10 |
|||
A=4 |
|||
B=0 |
|||
Print DetectDivisionByZero(lazy$(Z/B))=True |
|||
Print DetectDivisionByZero(lazy$(Z/A))=False |
|||
} |
|||
Checkit |
|||
</syntaxhighlight> |
|||
=={{header|M4}}== |
=={{header|M4}}== |
||
< |
<syntaxhighlight lang="m4">ifelse(eval(2/0),`',`detected divide by zero or some other error of some kind')</syntaxhighlight> |
||
Output, with standard output labeled "==>" and error output labeled "error==>": |
Output, with standard output labeled "==>" and error output labeled "error==>": |
||
Line 1,215: | Line 1,438: | ||
=={{header|Maple}}== |
=={{header|Maple}}== |
||
By default numeric exceptions raise errors which cannot be trapped by the usual <code>try...catch</code> mechanism. Instead numeric exceptions may be controlled by custom handling procedures. |
By default numeric exceptions raise errors which cannot be trapped by the usual <code>try...catch</code> mechanism. Instead numeric exceptions may be controlled by custom handling procedures. |
||
< |
<syntaxhighlight lang="maple">1/0; # Here is the default behavior.</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>Error, numeric exception: division by zero</pre> |
<pre>Error, numeric exception: division by zero</pre> |
||
Here is a simple custom handler being installed and used. |
Here is a simple custom handler being installed and used. |
||
< |
<syntaxhighlight lang="maple">NumericEventHandler( ':-division_by_zero' |
||
= proc() infinity; end proc ): |
= proc() infinity; end proc ): |
||
1/0; |
1/0; |
||
NumericStatus(':-division_by_zero'); # We may check the status flag</ |
NumericStatus(':-division_by_zero'); # We may check the status flag</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> infinity |
<pre> infinity |
||
Line 1,230: | Line 1,453: | ||
true</pre> |
true</pre> |
||
Alternatively, the custom handler could issue a warning or clear the status flag for that exception, as well as return some particular value. |
Alternatively, the custom handler could issue a warning or clear the status flag for that exception, as well as return some particular value. |
||
< |
<syntaxhighlight lang="maple">NumericEventHandler( ':-division_by_zero' |
||
= proc() |
= proc() |
||
WARNING("division by zero"); |
WARNING("division by zero"); |
||
Line 1,239: | Line 1,462: | ||
1/0; |
1/0; |
||
NumericStatus(':-division_by_zero');</ |
NumericStatus(':-division_by_zero');</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>Warning, division by zero |
<pre>Warning, division by zero |
||
Line 1,247: | Line 1,470: | ||
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
||
< |
<syntaxhighlight lang="mathematica">Check[2/0, Print["division by 0"], Power::infy]</syntaxhighlight> |
||
=={{header|MATLAB}}== |
=={{header|MATLAB}}== |
||
< |
<syntaxhighlight lang="matlab">function [isDividedByZero] = dividebyzero(numerator, denomenator) |
||
isDividedByZero = isinf( numerator/denomenator ); |
isDividedByZero = isinf( numerator/denomenator ); |
||
% If isDividedByZero equals 1, divide by zero occured.</ |
% If isDividedByZero equals 1, divide by zero occured.</syntaxhighlight> |
||
=={{header|Maxima}}== |
=={{header|Maxima}}== |
||
< |
<syntaxhighlight lang="maxima">f(a, b) := block([q: errcatch(a / b)], if emptyp(q) then 'error else q[1]); |
||
f(5, 6); |
f(5, 6); |
||
Line 1,261: | Line 1,484: | ||
f(5, 0;) |
f(5, 0;) |
||
'error</ |
'error</syntaxhighlight> |
||
=={{header|MAXScript}}== |
=={{header|MAXScript}}== |
||
< |
<syntaxhighlight lang="maxscript">if not bit.isFinite (<i>expression</i>) then...</syntaxhighlight> |
||
=={{header|min}}== |
|||
{{works with|min|0.19.3}} |
|||
The following operator will detect division by zero since the result will be infinity. |
|||
<syntaxhighlight lang="min">(/ inf ==) :div-zero?</syntaxhighlight> |
|||
Integer divison (that is, <code>div</code> and not <code>/</code>) by zero will cause min to exit with an uncatchable arithmetic error. |
|||
=={{header|MiniScript}}== |
|||
<syntaxhighlight lang="miniscript">number.isInfinite = function |
|||
return abs(self) == 1/0 |
|||
end function |
|||
number.isNaN = function |
|||
return self != self |
|||
end function |
|||
number.toBoolStr = function |
|||
if self == 0 then return "false" |
|||
return "true" |
|||
end function |
|||
checkDivByZero = function(a, b) |
|||
c = a / b |
|||
if c.isInfinite or c.isNaN then return true |
|||
return false |
|||
end function |
|||
print "Division by zero?" |
|||
print " 0 / 0 -> " + checkDivByZero( 0, 0).toBoolStr |
|||
print " 1 / 0 -> " + checkDivByZero( 1, 0).toBoolStr |
|||
print " 1 / 1 -> " + checkDivByZero( 1, 1).toBoolStr |
|||
print " -5 / 0 -> " + checkDivByZero(-5, 0).toBoolStr |
|||
print " -5 / 2 -> " + checkDivByZero(-5, 2).toBoolStr</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Division by zero? |
|||
0 / 0 -> true |
|||
1 / 0 -> true |
|||
1 / 1 -> false |
|||
-5 / 0 -> true |
|||
-5 / 2 -> false |
|||
</pre> |
|||
=={{header|mIRC Scripting Language}}== |
|||
<syntaxhighlight lang="mirc">var %n = $rand(0,1) |
|||
if ($calc(1/ %n) == $calc((1/ %n)+1)) { |
|||
echo -ag Divides By Zero |
|||
} |
|||
else { |
|||
echo -ag Does Not Divide By Zero |
|||
}</syntaxhighlight> |
|||
=={{header|MUMPS}}== |
=={{header|MUMPS}}== |
||
< |
<syntaxhighlight lang="mumps">DIV(A,B) ;Divide A by B, and watch for division by zero |
||
;The ANSI error code for division by zero is "M9". |
;The ANSI error code for division by zero is "M9". |
||
;$ECODE errors are surrounded by commas when set. |
;$ECODE errors are surrounded by commas when set. |
||
Line 1,277: | Line 1,551: | ||
DIVFIX |
DIVFIX |
||
IF $FIND($ECODE,",M9,")>1 WRITE !,"Error: Division by zero" SET $ECODE="" QUIT "" |
IF $FIND($ECODE,",M9,")>1 WRITE !,"Error: Division by zero" SET $ECODE="" QUIT "" |
||
QUIT "" ; Fall through for other errors</ |
QUIT "" ; Fall through for other errors</syntaxhighlight> |
||
Output:<pre> |
Output:<pre> |
||
USER>W $$DIV^ROSETTA(1,2) |
USER>W $$DIV^ROSETTA(1,2) |
||
Line 1,293: | Line 1,567: | ||
</pre> |
</pre> |
||
=={{header| |
=={{header|Nanoquery}}== |
||
<syntaxhighlight lang="nanoquery">def div_check(x, y) |
|||
<lang mirc>var %n = $rand(0,1) |
|||
try |
|||
if ($calc(1/ %n) == $calc((1/ %n)+1)) { |
|||
(x / y) |
|||
echo -ag Divides By Zero |
|||
return false |
|||
} |
|||
catch |
|||
else { |
|||
return true |
|||
echo -ag Does Not Divide By Zero |
|||
end |
|||
}</lang> |
|||
end</syntaxhighlight> |
|||
=={{header|Neko}}== |
|||
Float, non-float as infinity and catching an $idiv. *Not demonstrated in a function.* |
|||
<syntaxhighlight lang="actionscript">/** |
|||
Detect division by zero |
|||
*/ |
|||
var ans = 1.0 / 0.0 |
|||
if $isinfinite(ans) $print("division by zero: ", ans, "\n") |
|||
ans = 1 / 0 |
|||
if $isinfinite(ans) $print("division by zero: ", ans, "\n") |
|||
try $print($idiv(1, 0)) catch problem $print("idiv by zero: ", problem, "\n")</syntaxhighlight> |
|||
{{out}} |
|||
<pre>prompt$ nekoc divide-zero.neko |
|||
prompt$ neko divide-zero.n |
|||
division by zero: inf |
|||
division by zero: inf |
|||
idiv by zero: $idiv</pre> |
|||
=={{header|NetLogo}}== |
=={{header|NetLogo}}== |
||
< |
<syntaxhighlight lang="netlogo">;; Division by zero detection using CAREFULLY |
||
;; The CAREFULLY clause exists in NetLogo since version 2.0 |
;; The CAREFULLY clause exists in NetLogo since version 2.0 |
||
;; In prior versions of NetLogo, you must examine the divisor prior to performing the division. |
;; In prior versions of NetLogo, you must examine the divisor prior to performing the division. |
||
Line 1,325: | Line 1,623: | ||
] |
] |
||
[ output-print (word a " / " b " is not calculable" |
[ output-print (word a " / " b " is not calculable" |
||
]</ |
]</syntaxhighlight> |
||
=={{header|NetRexx}}== |
=={{header|NetRexx}}== |
||
< |
<syntaxhighlight lang="netrexx">/* NetRexx */ |
||
options replace format comments java crossref symbols nobinary |
options replace format comments java crossref symbols nobinary |
||
Line 1,351: | Line 1,649: | ||
say dividend '/' divisor '=' divide(dividend, divisor) |
say dividend '/' divisor '=' divide(dividend, divisor) |
||
return |
return |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre>netrexx.lang.DivideException: Divide by 0 |
<pre>netrexx.lang.DivideException: Divide by 0 |
||
Line 1,358: | Line 1,656: | ||
at zz.divide(zz.nrx:20) |
at zz.divide(zz.nrx:20) |
||
at zz.main(zz.nrx:47)</pre> |
at zz.main(zz.nrx:47)</pre> |
||
=={{header|NewLISP}}== |
|||
<syntaxhighlight lang="newlisp">#! /usr/local/bin/newlisp |
|||
(define (check-division x y) |
|||
(catch (/ x y) 'check-zero) |
|||
(if (not (integer? check-zero)) |
|||
(setq check-zero "Division by zero.")) |
|||
check-zero |
|||
) |
|||
(println (check-division 10 4)) |
|||
(println (check-division 4 0)) |
|||
(println (check-division 20 5)) |
|||
(println (check-division 11 0)) |
|||
(exit)</syntaxhighlight> |
|||
Output: |
|||
<pre> |
|||
2 |
|||
Division by zero. |
|||
4 |
|||
Division by zero. |
|||
</pre> |
|||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
<lang nim># In debug builds division by zero exceptions are thrown by default, in release |
|||
In version 1.4 and later, Nim makes a distinction between errors and defects. The first ones are exceptions which can be caught using an except clause. The second ones are non “catchable” exceptions which cause the program to abort. In version 1.4, by default, defects can still be caught, but this behavior is likely to change in next versions. Note that the distinction between errors and defects allow to process defects much more efficiently than errors. |
|||
# builds not. We can still enable them explicitly. |
|||
{.push overflowChecks: on.} |
|||
Division by zero is now a defect and DivByZeroError is deprecated and replaced by DivByZeroDefect. So, the following program which catches a DivByZeroDefect is likely to fail to compile or execute correctly in future versions (but it is also very likely that using option <code>--panics:off</code> will restore the previous behavior). |
|||
In debug mode (the default), all checks are activated. In release mode (<code>-d:release</code>), checks are also activated. In danger mode (<code>-d:danger</code>) all checks are deactivated. |
|||
It is possible to declare the checks to activate or deactivate in some parts of code using a pragma, as in the following example. |
|||
<syntaxhighlight lang="nim">{.push overflowChecks: on.} |
|||
proc divCheck(x, y): bool = |
proc divCheck(x, y): bool = |
||
try: |
try: |
||
discard x div y |
discard x div y |
||
except |
except DivByZeroDefect: |
||
return true |
return true |
||
return false |
return false |
||
{.pop.} # Restore default check settings |
{.pop.} # Restore default check settings |
||
echo divCheck(2, 0)</ |
echo divCheck(2, 0)</syntaxhighlight> |
||
=={{header|NS-HUBASIC}}== |
|||
<syntaxhighlight lang="ns-hubasic">10 ON ERROR GOTO 40 |
|||
20 PRINT 1/0 |
|||
30 END |
|||
40 IF ERR = 10 THEN PRINT "DIVISION BY ZERO IN LINE"ERL |
|||
50 RESUME 30</syntaxhighlight> |
|||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
Detection on integers by catching an exception: |
Detection on integers by catching an exception: |
||
< |
<syntaxhighlight lang="ocaml">let div_check x y = |
||
try |
try |
||
ignore (x / y); |
ignore (x / y); |
||
false |
false |
||
with Division_by_zero -> |
with Division_by_zero -> |
||
true</ |
true</syntaxhighlight> |
||
Detection on floats by checking for infiniteness: |
Detection on floats by checking for infiniteness: |
||
< |
<syntaxhighlight lang="ocaml">let div_check x y = |
||
classify_float (x /. y) = FP_infinite</ |
classify_float (x /. y) = FP_infinite</syntaxhighlight> |
||
=={{header|Oforth}}== |
|||
<lang Oforth>: divideCheck(n) |
|||
| e | |
|||
try: e [ 128 n / ] when: [ "Zero detected..." . ] |
|||
"Leaving" println ;</lang> |
|||
=={{header|Octave}}== |
=={{header|Octave}}== |
||
Line 1,397: | Line 1,727: | ||
Dividing by zero raises a warning (a warning does not stop the execution), not an error (and the given answer is ''Inf''inity), so it's not possible to use a try-catch construct; we can however check for the lastwarn if the answer is Inf. |
Dividing by zero raises a warning (a warning does not stop the execution), not an error (and the given answer is ''Inf''inity), so it's not possible to use a try-catch construct; we can however check for the lastwarn if the answer is Inf. |
||
< |
<syntaxhighlight lang="octave">d = 5/0; |
||
if ( isinf(d) ) |
if ( isinf(d) ) |
||
if ( index(lastwarn(), "division by zero") > 0 ) |
if ( index(lastwarn(), "division by zero") > 0 ) |
||
error("division by zero") |
error("division by zero") |
||
endif |
endif |
||
endif</ |
endif</syntaxhighlight> |
||
=={{header|Oforth}}== |
|||
<syntaxhighlight lang="oforth">: divideCheck(n) |
|||
| e | |
|||
try: e [ 128 n / ] when: [ "Zero detected..." . ] |
|||
"Leaving" println ;</syntaxhighlight> |
|||
=={{header|Ol}}== |
|||
Division by inexact zero produces Infinity (`+inf.0` and `-inf.0`) values, but division by exact zero (like `(/ n 0)`) - produces runtime error! |
|||
<syntaxhighlight lang="scheme"> |
|||
(define (safediv a b) |
|||
(if (eq? (type b) type-complex) |
|||
(/ a b) ; complex can't be 0 |
|||
(let ((z (/ 1 (inexact b)))) |
|||
(unless (or (equal? z +inf.0) (equal? z -inf.0)) |
|||
(/ a b))))) |
|||
; testing: |
|||
(for-each (lambda (x) |
|||
(if x (print x) (print "division by zero detected"))) |
|||
(list |
|||
(safediv 1 5) ; => 1/5 |
|||
(safediv 2 0) ; => division by zero detected |
|||
(safediv 3 1+2i) ; => 3/5-6/5i |
|||
(safediv 4 0+i) ; => 0-4i |
|||
(safediv 5 7/5) ; => 25/7 |
|||
)) |
|||
</syntaxhighlight> |
|||
=={{header|ooRexx}}== |
=={{header|ooRexx}}== |
||
< |
<syntaxhighlight lang="oorexx">/* REXX ************************************************************** |
||
* program demonstrates detects and handles division by zero. |
* program demonstrates detects and handles division by zero. |
||
* translated from REXX: |
* translated from REXX: |
||
Line 1,422: | Line 1,782: | ||
Say sourceline(sigl) |
Say sourceline(sigl) |
||
Say 'rc='rc '('errortext(rc)')' |
Say 'rc='rc '('errortext(rc)')' |
||
Exit 12</ |
Exit 12</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>Syntax raised in line 11 |
<pre>Syntax raised in line 11 |
||
Line 1,430: | Line 1,790: | ||
=={{header|Oz}}== |
=={{header|Oz}}== |
||
For integer division only. |
For integer division only. |
||
< |
<syntaxhighlight lang="oz">try |
||
{Show 42 div 0} |
{Show 42 div 0} |
||
catch error(kernel(div0 ...) ...) then |
catch error(kernel(div0 ...) ...) then |
||
{System.showInfo "Division by zero detected."} |
{System.showInfo "Division by zero detected."} |
||
end</ |
end</syntaxhighlight> |
||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
Pari/GP version 2.7 introduces <code>iferr()</code>. The given <code>err</code> variable is lexically bound in the recovery code and in the optional predicate (what to trap, default all errors). Error type <code>e_INV</code> is division by zero. |
Pari/GP version 2.7 introduces <code>iferr()</code>. The given <code>err</code> variable is lexically bound in the recovery code and in the optional predicate (what to trap, default all errors). Error type <code>e_INV</code> is division by zero. |
||
< |
<syntaxhighlight lang="parigp">iferr(1/0, |
||
err, |
err, |
||
print("division by 0"); print("or other non-invertible divisor"), |
print("division by 0"); print("or other non-invertible divisor"), |
||
errname(err) == "e_INV");</ |
errname(err) == "e_INV");</syntaxhighlight> |
||
Or the previous <code>trap()</code>, |
Or the previous <code>trap()</code>, |
||
< |
<syntaxhighlight lang="parigp">trap(,"division by 0",m/n)</syntaxhighlight> |
||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
Line 1,453: | Line 1,813: | ||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
This function returns true iff its second argument is zero. |
This function returns true iff its second argument is zero. |
||
< |
<syntaxhighlight lang="perl">sub div_check |
||
{local $@; |
{local $@; |
||
eval {$_[0] / $_[1]}; |
eval {$_[0] / $_[1]}; |
||
$@ and $@ =~ /division by zero/;}</ |
$@ and $@ =~ /division by zero/;}</syntaxhighlight> |
||
=={{header|Perl 6}}== |
|||
<lang perl6>sub div($a, $b){ |
|||
my $r; |
|||
try { |
|||
$r = $a / $b; |
|||
CATCH { |
|||
say "tried to divide by zero !" if $! ~~ "Divide by zero"; |
|||
} |
|||
} |
|||
return $r // fail; |
|||
} |
|||
say div(10,2); # 5 |
|||
say div(1,0); # Inf, 1/0 constants are substituted for Infinity |
|||
say div(1, sin(0)); # undef, and prints "tried to divide by zero" |
|||
</lang> |
|||
===Using Multi Method Dispatch=== |
|||
<lang perl6>multi div($a, $b){ return $a / $b } |
|||
multi div($a, $b where { $b == 0 }){ |
|||
say 'lolicheatsyou'; |
|||
return 1; |
|||
} |
|||
say div(1, sin(0)); # prints "lolicheatsyou" newline "1" |
|||
</lang> |
|||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
{{libheader|Phix/basics}} |
|||
<lang Phix>try |
|||
<!--<syntaxhighlight lang="phix">--> |
|||
integer i = 1/0 |
|||
<span style="color: #008080;">try</span> |
|||
catch e |
|||
<span style="color: #004080;">integer</span> <span style="color: #000000;">i</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1<span style="color: #0000FF;">/<span style="color: #000000;">0</span> |
|||
?e[E_USER] |
|||
<span style="color: #008080;">catch</span> <span style="color: #000000;">e</span> |
|||
end try |
|||
<span style="color: #0000FF;">?<span style="color: #000000;">e<span style="color: #0000FF;">[<span style="color: #000000;">E_USER<span style="color: #0000FF;">]</span> |
|||
puts(1,"still running...\n")</lang> |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">try</span> |
|||
<span style="color: #7060A8;">puts<span style="color: #0000FF;">(<span style="color: #000000;">1<span style="color: #0000FF;">,<span style="color: #008000;">"still running...\n"<span style="color: #0000FF;">) |
|||
<!--</syntaxhighlight>--> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,501: | Line 1,836: | ||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
This function returns true iff its second argument is zero. |
This function returns true iff its second argument is zero. |
||
< |
<syntaxhighlight lang="php">function div_check($x, $y) { |
||
@trigger_error(''); // a dummy to detect when error didn't occur |
@trigger_error(''); // a dummy to detect when error didn't occur |
||
@($x / $y); |
@($x / $y); |
||
$e = error_get_last(); |
$e = error_get_last(); |
||
return $e['message'] != ''; |
return $e['message'] != ''; |
||
}</ |
}</syntaxhighlight> |
||
< |
<syntaxhighlight lang="php">function div_check($x, $y) { |
||
return @($x / $y) === FALSE; // works at least in PHP/5.2.6-3ubuntu4.5 |
return @($x / $y) === FALSE; // works at least in PHP/5.2.6-3ubuntu4.5 |
||
}</ |
}</syntaxhighlight> |
||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang="picolisp">(catch '("Div/0") (/ A B))</syntaxhighlight> |
||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
< |
<syntaxhighlight lang="pli">Proc DivideDZ(a,b) Returns(Float Bin(33)); |
||
Dcl (a,b,c) Float Bin(33); |
Dcl (a,b,c) Float Bin(33); |
||
On ZeroDivide GoTo MyError; |
On ZeroDivide GoTo MyError; |
||
Line 1,525: | Line 1,860: | ||
End DivideDZ; |
End DivideDZ; |
||
xx=DivideDZ(1,0);</ |
xx=DivideDZ(1,0);</syntaxhighlight> |
||
=={{header|PL/SQL}}== |
=={{header|PL/SQL}}== |
||
< |
<syntaxhighlight lang="plsql">FUNCTION divide(n1 IN NUMBER, n2 IN NUMBER) |
||
RETURN BOOLEAN |
RETURN BOOLEAN |
||
IS |
IS |
||
Line 1,538: | Line 1,873: | ||
WHEN ZERO_DIVIDE THEN |
WHEN ZERO_DIVIDE THEN |
||
RETURN(true); |
RETURN(true); |
||
end divide;</ |
end divide;</syntaxhighlight> |
||
< |
<syntaxhighlight lang="pl/sql">divide(0,1) --false |
||
divide(1,0) --true, division by zero</ |
divide(1,0) --true, division by zero</syntaxhighlight> |
||
=={{header|Plain English}}== |
|||
{{libheader|Plain English-output}} |
|||
When dividing by zero in Plain English, it explicitly returns 2147483647. The decider below detects division by zero by checking if it returns 2147483647. |
|||
<syntaxhighlight lang="text"> |
|||
To run: |
|||
Start up. |
|||
If 1 and 0 does cause division error, write "Division by zero found" to the output. |
|||
Wait for the escape key. |
|||
Shut down. |
|||
To decide if a number and another number does cause division error: |
|||
Put the number divided by the other number into a third number. |
|||
If the third number is the largest number, say yes. |
|||
Say no. |
|||
</syntaxhighlight> |
|||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
<syntaxhighlight lang="powershell"> |
|||
<lang PowerShell> |
|||
function div ($a, $b) { |
function div ($a, $b) { |
||
try{$a/$b} |
try{$a/$b} |
||
Line 1,551: | Line 1,902: | ||
div 10 2 |
div 10 2 |
||
div 1 0 |
div 1 0 |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
|||
<b>Output:</b> |
|||
<pre> |
<pre> |
||
5 |
5 |
||
Bad parameters: $a = 1 and $b = 0 |
Bad parameters: $a = 1 and $b = 0 |
||
</pre> |
|||
=={{header|Prolog}}== |
|||
<syntaxhighlight lang="prolog"> |
|||
div(A, B, C, Ex) :- |
|||
catch((C is A/B), Ex, (C = infinity)). |
|||
</syntaxhighlight> |
|||
{{Out}} |
|||
<pre> |
|||
?- div(10, 5, X, Ex). |
|||
X = 2. |
|||
?- div(1, 0, X, Ex). |
|||
X = infinity, |
|||
Ex = error(evaluation_error(zero_divisor), context((/)/2, _2950)). |
|||
</pre> |
</pre> |
||
Line 1,561: | Line 1,927: | ||
Floating point division yields inf or nan values as appropriate (if the FPU supports IEEE 754): |
Floating point division yields inf or nan values as appropriate (if the FPU supports IEEE 754): |
||
< |
<syntaxhighlight lang="pure">> 1/0, -1/0, 0/0; |
||
inf,-inf,nan</ |
inf,-inf,nan</syntaxhighlight> |
||
It's possible to check for these values as follows: |
It's possible to check for these values as follows: |
||
< |
<syntaxhighlight lang="pure">> inf_or_nan x = infp x || nanp x; |
||
> map inf_or_nan [1/0, -1/0, 0/0]; |
> map inf_or_nan [1/0, -1/0, 0/0]; |
||
[1,1,1]</ |
[1,1,1]</syntaxhighlight> |
||
In contrast, integer division by zero raises an exception which can be caught as follows: |
In contrast, integer division by zero raises an exception which can be caught as follows: |
||
< |
<syntaxhighlight lang="pure">> divide n m = catch (\_ -> "divide by 0") (n div m); |
||
> divide 0 1; |
> divide 0 1; |
||
0 |
0 |
||
> divide 1 0; |
> divide 1 0; |
||
"divide by 0"</ |
"divide by 0"</syntaxhighlight> |
||
=={{header|Python}}== |
=={{header|Python}}== |
||
< |
<syntaxhighlight lang="python">def div_check(x, y): |
||
try: |
try: |
||
x / y |
x / y |
||
Line 1,585: | Line 1,951: | ||
return True |
return True |
||
else: |
else: |
||
return False</ |
return False</syntaxhighlight> |
||
=={{header|Q}}== |
|||
Division by zero does not raise an error, instead it results in an infinity (<tt>0w</tt> or <tt>-0w</tt>) or NaN (<tt>0n</tt>). |
|||
<syntaxhighlight lang="q">r:x%0 |
|||
?[1=sum r=(0n;0w;-0w);"division by zero detected";()]</syntaxhighlight> |
|||
=={{header|R}}== |
=={{header|R}}== |
||
Division by zero does not raise an error nor a warning. Division of a non-zero value by zero returns infinity. Division of zero by zero returns NaN; Whether the result is not finite can be checked: |
Division by zero does not raise an error nor a warning. Division of a non-zero value by zero returns infinity. Division of zero by zero returns NaN; Whether the result is not finite can be checked: |
||
< |
<syntaxhighlight lang="rsplus">d <- 5/0 |
||
if ( !is.finite(d) ) { |
if ( !is.finite(d) ) { |
||
# it is Inf, -Inf, or NaN |
# it is Inf, -Inf, or NaN |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
Line 1,598: | Line 1,970: | ||
In Racket, the division by zero exception can be caught directly: |
In Racket, the division by zero exception can be caught directly: |
||
< |
<syntaxhighlight lang="racket"> |
||
#lang racket |
#lang racket |
||
Line 1,604: | Line 1,976: | ||
(λ (e) (displayln "Divided by zero"))]) |
(λ (e) (displayln "Divided by zero"))]) |
||
(/ 1 0)) |
(/ 1 0)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Raku}}== |
|||
(formerly Perl 6) |
|||
====Try/Catch==== |
|||
<syntaxhighlight lang="raku" line>sub div($a, $b) { |
|||
my $r; |
|||
try { |
|||
$r = $a / $b; |
|||
CATCH { |
|||
default { note "Unexpected exception, $_" } |
|||
} |
|||
} |
|||
return $r // Nil; |
|||
} |
|||
say div(10,2); |
|||
say div(1, sin(0));</syntaxhighlight> |
|||
{{out}} |
|||
<pre>5 |
|||
Unexpected exception, Attempt to divide 1 by zero using / |
|||
Nil</pre> |
|||
====Multi Method Dispatch==== |
|||
<syntaxhighlight lang="raku" line>multi div($a, $b) { return $a / $b } |
|||
multi div($a, $b where { $b == 0 }) { note 'Attempt to divide by zero.'; return Nil } |
|||
say div(10, 2); |
|||
say div(1, sin(0));</syntaxhighlight> |
|||
{{out}} |
|||
<pre>5 |
|||
Attempt to divide by zero. |
|||
Nil</pre> |
|||
=={{header|REBOL}}== |
=={{header|REBOL}}== |
||
< |
<syntaxhighlight lang="rebol">REBOL [ |
||
Title: "Detect Divide by Zero" |
Title: "Detect Divide by Zero" |
||
Date: 2009-12-16 |
|||
Author: oofoe |
|||
URL: http://rosettacode.org/wiki/Divide_by_Zero_Detection |
URL: http://rosettacode.org/wiki/Divide_by_Zero_Detection |
||
] |
] |
||
Line 1,635: | Line 2,036: | ||
div-check 12 2 ; An ordinary calculation. |
div-check 12 2 ; An ordinary calculation. |
||
div-check 6 0 ; This will detect divide by zero. |
div-check 6 0 ; This will detect divide by zero. |
||
div-check "7" 0.0001 ; Other errors can be caught as well.</ |
div-check "7" 0.0001 ; Other errors can be caught as well.</syntaxhighlight> |
||
Output: |
Output: |
||
Line 1,647: | Line 2,048: | ||
<br>This version isn't really a function so much as it is a method. |
<br>This version isn't really a function so much as it is a method. |
||
<br>Also, a ''function'' and a ''subroutine'' doesn't have that much of a distinction in the REXX language. |
<br>Also, a ''function'' and a ''subroutine'' doesn't have that much of a distinction in the REXX language. |
||
< |
<syntaxhighlight lang="rexx">/*REXX program demonstrates detection and handling division by zero. */ |
||
signal on syntax /*handle all REXX syntax errors. */ |
signal on syntax /*handle all REXX syntax errors. */ |
||
x = sourceline() /*being cute, x=is the size of this pgm*/ |
x = sourceline() /*being cute, x=is the size of this pgm*/ |
||
Line 1,669: | Line 2,070: | ||
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
||
syntax: @=sigl; call err 'REXX program' condition("C") 'error', condition('D'), , |
syntax: @=sigl; call err 'REXX program' condition("C") 'error', condition('D'), , |
||
'REXX source statement (line' sigl"):", sourceLine(sigl)</ |
'REXX source statement (line' sigl"):", sourceLine(sigl)</syntaxhighlight> |
||
{{out|output|text=}} |
{{out|output|text=}} |
||
<pre> |
<pre> |
||
Line 1,678: | Line 2,079: | ||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
Try |
Try |
||
see 9/0 |
see 9/0 |
||
Line 1,684: | Line 2,085: | ||
see "Catch!" + nl + cCatchError |
see "Catch!" + nl + cCatchError |
||
Done |
Done |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|RPGIV}}== |
=={{header|RPGIV}}== |
||
< |
<syntaxhighlight lang="rpgiv"> |
||
dcl-c DIVIDE_BY_ZERO 00102; |
dcl-c DIVIDE_BY_ZERO 00102; |
||
Line 1,705: | Line 2,106: | ||
*inlr = *on; |
*inlr = *on; |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|RPL}}== |
|||
RPL provides targeted error detection and handling. In case of a division by zero, rather than displaying an error message, the program delivers the attempted arithmetic operation as an expression to be further processed. |
|||
≪ '''IFERR''' / '''THEN''' |
|||
SWAP "'" SWAP →STR + "/" + SWAP →STR + STR→ |
|||
'''END''' |
|||
≫ '<span style="color:blue">DIV</span>' STO |
|||
6 2 <span style="color:blue">DIV</span> |
|||
4 0 <span style="color:blue">DIV</span> |
|||
{{out}} |
|||
<pre> |
|||
2: 3 |
|||
1: '4/0' |
|||
</pre> |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
This only checks integer division by zero. |
This only checks integer division by zero. |
||
< |
<syntaxhighlight lang="ruby">def div_check(x, y) |
||
begin |
begin |
||
x / y |
x / y |
||
Line 1,720: | Line 2,134: | ||
false |
false |
||
end |
end |
||
end</ |
end</syntaxhighlight> |
||
Ruby allows division by zero if either operand is a Float. |
Ruby allows division by zero if either operand is a Float. |
||
< |
<syntaxhighlight lang="ruby">irb(main):010:0> div_check(5, 0) |
||
=> true |
=> true |
||
irb(main):011:0> div_check(5.0, 0) |
irb(main):011:0> div_check(5.0, 0) |
||
=> false</ |
=> false</syntaxhighlight> |
||
---- |
---- |
||
Line 1,735: | Line 2,149: | ||
{{works with|Ruby|1.9}} |
{{works with|Ruby|1.9}} |
||
< |
<syntaxhighlight lang="ruby">def div_check(x, y) |
||
begin |
begin |
||
x.div y |
x.div y |
||
Line 1,743: | Line 2,157: | ||
false |
false |
||
end |
end |
||
end</ |
end</syntaxhighlight> |
||
< |
<syntaxhighlight lang="ruby">irb(main):010:0> div_check(5, 0) |
||
=> true |
=> true |
||
irb(main):011:0> div_check(5.0, 0) |
irb(main):011:0> div_check(5.0, 0) |
||
=> true</ |
=> true</syntaxhighlight> |
||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
< |
<syntaxhighlight lang="rust">fn test_division(numerator: u32, denominator: u32) { |
||
match numerator.checked_div(denominator) { |
match numerator.checked_div(denominator) { |
||
Some(result) => println!("{} / {} = {}", numerator, denominator, result), |
Some(result) => println!("{} / {} = {}", numerator, denominator, result), |
||
Line 1,761: | Line 2,175: | ||
test_division(5, 4); |
test_division(5, 4); |
||
test_division(4, 0); |
test_division(4, 0); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
Line 1,767: | Line 2,181: | ||
as it is not needed. The method would get optimized to |
as it is not needed. The method would get optimized to |
||
always return false. |
always return false. |
||
< |
<syntaxhighlight lang="scala">object DivideByZero extends Application { |
||
def check(x: Int, y: Int): Boolean = { |
def check(x: Int, y: Int): Boolean = { |
||
Line 1,783: | Line 2,197: | ||
println("divided by zero = " + check(1, 0)) |
println("divided by zero = " + check(1, 0)) |
||
def check1(x: Int, y: Int): Boolean = { |
|||
}</lang> |
|||
import scala.util.Try |
|||
Try(y/x).isFailure |
|||
} |
|||
println("divided by zero = " + check1(1, 0)) |
|||
}</syntaxhighlight> |
|||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
Integer division by zero raises NUMERIC_ERROR. |
Integer division by zero raises NUMERIC_ERROR. |
||
Floating point division by zero returns [http://seed7.sourceforge.net/libraries/float.htm#Infinity Infinity] or -Infinity. |
Floating point division by zero returns [http://seed7.sourceforge.net/libraries/float.htm#Infinity Infinity] or -Infinity. |
||
< |
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
||
include "float.s7i"; |
include "float.s7i"; |
||
Line 1,819: | Line 2,239: | ||
doDivide(10.0, 8.0); |
doDivide(10.0, 8.0); |
||
doDivide(1.0, 0.0); |
doDivide(1.0, 0.0); |
||
end func;</ |
end func;</syntaxhighlight> |
||
Output: |
Output: |
||
Line 1,831: | Line 2,251: | ||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
The numerical system of Sidef evaluates `x/0` to `+/-Inf`. |
The numerical system of Sidef evaluates `x/0` to `+/-Inf`. |
||
< |
<syntaxhighlight lang="ruby">func div_check(a, b){ |
||
var result = a/b |
var result = a/b |
||
result.abs == Inf ? nil : result |
result.abs == Inf ? nil : result |
||
Line 1,837: | Line 2,257: | ||
say div_check(10, 2) # 5 |
say div_check(10, 2) # 5 |
||
say div_check(1, 0) # nil (detected)</ |
say div_check(1, 0) # nil (detected)</syntaxhighlight> |
||
Alternatively, we can do: |
Alternatively, we can do: |
||
< |
<syntaxhighlight lang="ruby">func div_check(a, b){ |
||
Perl.eval("#{a} / #{b}") |
Perl.eval("#{a} / #{b}") |
||
} |
} |
||
say div_check(10, 2) # 5 |
say div_check(10, 2) # 5 |
||
say div_check(1, 0) # nil (detected)</ |
say div_check(1, 0) # nil (detected)</syntaxhighlight> |
||
=={{header|Slate}}== |
=={{header|Slate}}== |
||
< |
<syntaxhighlight lang="slate">[ 1 / 0 ] on: Error do: [|:err| err return: PositiveInfinity].</syntaxhighlight> |
||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
The behavior is the same for all number types (Integer, Float, Fraction, etc.). |
|||
ZeroDivision raises an exception which can be caught to abort or proceed with a repair-value. |
|||
{{works with|Smalltalk/X}} |
|||
<syntaxhighlight lang="smalltalk">|didDivideByZero a b| |
|||
didDivideByZero := false. |
|||
a := 10. |
|||
b := 0. |
|||
[ |
|||
a/b |
|||
] on: ZeroDivide do:[:ex | |
|||
'you tried to divide %P by zero\n' printf:{ex suspendedContext receiver} on:Transcript. |
|||
didDivideByZero := true. |
|||
]. |
|||
didDivideByZero ifTrue:[ |
|||
Transcript show:'bad bad bad, but I already told you in the handler'. |
|||
].</syntaxhighlight> |
|||
Note: works in all Smalltalks: printf is available in the public domain printfScanf package (or already included in your dialect). |
|||
Alternative version, which gets any block as argument, evaluates it and returns true, if ZeroDivide happened (works in all Smalltalks): |
|||
{{works with|Squeak}} |
{{works with|Squeak}} |
||
{{works with|Smalltalk/X}} |
{{works with|Smalltalk/X}} |
||
<lang |
<syntaxhighlight lang="smalltalk">testZeroDivide := |
||
[:aBlock | |
|||
[aBlock value. false] on: ZeroDivide do: [true]. |
|||
[ |
|||
aBlock value. |
|||
false |
|||
] on: ZeroDivide do: [true]. |
|||
]. |
|||
"Testing" |
"Testing" |
||
testZeroDivide value: [2/1] "------> false" |
|||
testZeroDivide value: [2/0] "------> true"</syntaxhighlight> |
|||
of course, as ZeroDivide inherits from Error, you could also write [...] on: |
of course, as ZeroDivide inherits from Error, you could also write <syntaxhighlight lang="smalltalk">[...] on:Error do: [...]</syntaxhighlight>thereby catching ANY error (as done in some other code examples here). |
||
You can also provide an alternative value from the exception handler: |
|||
{{works with|Smalltalk/X}} |
|||
<syntaxhighlight lang="smalltalk">|a b result| |
|||
a := 10. b := 0. |
|||
result := [a / b] on:ZeroDivide do:[:ex | ex proceedWith:Float infinity]. |
|||
Transcript showCR:result.</syntaxhighlight> |
|||
will show "inf" on the console window. |
|||
=={{header|SNOBOL4}}== |
=={{header|SNOBOL4}}== |
||
Line 1,872: | Line 2,325: | ||
Using setexit( ) to trap and ignore division by zero. |
Using setexit( ) to trap and ignore division by zero. |
||
< |
<syntaxhighlight lang="snobol4"> define('zdiv(x,y)') :(zdiv_end) |
||
zdiv &errlimit = 1; setexit(.ztrap) |
zdiv &errlimit = 1; setexit(.ztrap) |
||
zdiv = x / y :(return) |
zdiv = x / y :(return) |
||
Line 1,884: | Line 2,337: | ||
output = '1.0/0.0 = ' zdiv(1.0,0.0) ;* Reals zero |
output = '1.0/0.0 = ' zdiv(1.0,0.0) ;* Reals zero |
||
output = 'Zero checks complete' |
output = 'Zero checks complete' |
||
end</ |
end</syntaxhighlight> |
||
Output: |
Output: |
||
Line 1,892: | Line 2,345: | ||
1.0/0.0 = Division by zero |
1.0/0.0 = Division by zero |
||
Zero checks complete</pre> |
Zero checks complete</pre> |
||
=={{header|SQL PL}}== |
|||
{{works with|Db2 LUW}} version 9.7 or higher. |
|||
With SQL PL: |
|||
<syntaxhighlight lang="sql pl"> |
|||
--#SET TERMINATOR @ |
|||
SET SERVEROUTPUT ON@ |
|||
CREATE OR REPLACE FUNCTION DIVISION( |
|||
IN NUMERATOR DECIMAL(5, 3), |
|||
IN DENOMINATOR DECIMAL(5, 3) |
|||
) RETURNS SMALLINT |
|||
BEGIN |
|||
DECLARE RET SMALLINT DEFAULT 1; |
|||
DECLARE TMP DECIMAL(5, 3); |
|||
DECLARE CONTINUE HANDLER FOR SQLSTATE '22012' |
|||
SET RET = 1; |
|||
SET RET = 0; |
|||
SET TMP = NUMERATOR / DENOMINATOR; |
|||
RETURN RET; |
|||
END @ |
|||
VALUES DIVISION(10, 2)@ |
|||
VALUES DIVISION(10, 3)@ |
|||
VALUES DIVISION(10, 0)@ |
|||
</syntaxhighlight> |
|||
Output: |
|||
<pre> |
|||
db2 -td@ |
|||
db2 => CREATE OR REPLACE FUNCTION DIVISION( |
|||
... |
|||
db2 (cont.) => END @ |
|||
DB20000I The SQL command completed successfully. |
|||
VALUES DIVISION(10, 2) |
|||
1 |
|||
------ |
|||
0 |
|||
1 record(s) selected. |
|||
VALUES DIVISION(10, 3) |
|||
1 |
|||
------ |
|||
0 |
|||
1 record(s) selected. |
|||
VALUES DIVISION(10, 0) |
|||
1 |
|||
------ |
|||
1 |
|||
1 record(s) selected. |
|||
</pre> |
|||
=={{header|Standard ML}}== |
=={{header|Standard ML}}== |
||
Detection on integers by catching an exception: |
Detection on integers by catching an exception: |
||
< |
<syntaxhighlight lang="sml">fun div_check (x, y) = ( |
||
ignore (x div y); |
ignore (x div y); |
||
false |
false |
||
) handle Div => true</ |
) handle Div => true</syntaxhighlight> |
||
Detection on floats by checking for infiniteness: |
Detection on floats by checking for infiniteness: |
||
< |
<syntaxhighlight lang="sml">fun div_check (x, y) = |
||
not (Real.isFinite (x / y))</ |
not (Real.isFinite (x / y))</syntaxhighlight> |
||
=={{header|Stata}}== |
=={{header|Stata}}== |
||
Line 1,908: | Line 2,423: | ||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
< |
<syntaxhighlight lang="tcl">proc div_check {x y} { |
||
if {[catch {expr {$x/$y}} result] == 0} { |
if {[catch {expr {$x/$y}} result] == 0} { |
||
puts "valid division: $x/$y=$result" |
puts "valid division: $x/$y=$result" |
||
Line 1,922: | Line 2,437: | ||
foreach denom {1 0 foo} { |
foreach denom {1 0 foo} { |
||
div_check 42 $denom |
div_check 42 $denom |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>valid division: 42/1=42 |
<pre>valid division: 42/1=42 |
||
Line 1,930: | Line 2,445: | ||
It is easier to trap such errors in Tcl 8.6, which has an additional control structure for exception processing: |
It is easier to trap such errors in Tcl 8.6, which has an additional control structure for exception processing: |
||
< |
<syntaxhighlight lang="tcl">proc div_check {x y} { |
||
try { |
try { |
||
puts "valid division: $x/$y=[expr {$x/$y}]" |
puts "valid division: $x/$y=[expr {$x/$y}]" |
||
Line 1,944: | Line 2,459: | ||
foreach {num denom} {42 1 42 0 42.0 0.0 0 0 0.0 0.0 0 foo} { |
foreach {num denom} {42 1 42 0 42.0 0.0 0 0 0.0 0.0 0 foo} { |
||
div_check $num $denom |
div_check $num $denom |
||
}</ |
}</syntaxhighlight> |
||
which produces the {{out}} |
which produces the {{out}} |
||
<pre>valid division: 42/1=42 |
<pre>valid division: 42/1=42 |
||
Line 1,956: | Line 2,471: | ||
=={{header|TXR}}== |
=={{header|TXR}}== |
||
< |
<syntaxhighlight lang="txr">@(do (defun div-check (x y) |
||
(catch (/ x y) |
(catch (/ x y) |
||
(numeric_error (msg) |
(numeric_error (msg) |
||
'div-check-failed)))) |
'div-check-failed)))) |
||
@(bind good @(div-check 32 8)) |
@(bind good @(div-check 32 8)) |
||
@(bind bad @(div-check 42 0))</ |
@(bind bad @(div-check 42 0))</syntaxhighlight> |
||
Run: |
Run: |
||
Line 1,971: | Line 2,486: | ||
=={{header|Ursa}}== |
=={{header|Ursa}}== |
||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang="ursa">def div_check (int x, int y) |
||
try |
try |
||
/ x y |
/ x y |
||
Line 1,978: | Line 2,493: | ||
return true |
return true |
||
end try |
end try |
||
end</ |
end</syntaxhighlight> |
||
=={{header|VAX Assembly}}== |
=={{header|VAX Assembly}}== |
||
< |
<syntaxhighlight lang="vax assembly">65 64 69 76 69 64 00000008'010E0000' 0000 1 desc: .ascid "divide by zero" |
||
6F 72 65 7A 20 79 62 20 000E |
6F 72 65 7A 20 79 62 20 000E |
||
0000 0016 2 .entry handler,0 |
0000 0016 2 .entry handler,0 |
||
Line 1,995: | Line 2,511: | ||
$ run dv |
$ run dv |
||
divide by zero |
divide by zero |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|VBA}}== |
=={{header|VBA}}== |
||
<syntaxhighlight lang="vb"> |
|||
<lang vb> |
|||
Option Explicit |
Option Explicit |
||
Line 2,011: | Line 2,528: | ||
If Err = 0 Then CatchDivideByZero = True |
If Err = 0 Then CatchDivideByZero = True |
||
On Error GoTo 0 |
On Error GoTo 0 |
||
End Function</ |
End Function</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>Error |
<pre>Error |
||
15,2</pre> |
15,2</pre> |
||
=={{header|VBScript}}== |
=={{header|VBScript}}== |
||
<syntaxhighlight lang="vb"> |
|||
<lang vb> |
|||
Function div(num,den) |
Function div(num,den) |
||
On Error Resume Next |
On Error Resume Next |
||
Line 2,031: | Line 2,548: | ||
WScript.StdOut.WriteLine div(6,0) |
WScript.StdOut.WriteLine div(6,0) |
||
WScript.StdOut.WriteLine div(7,-4) |
WScript.StdOut.WriteLine div(7,-4) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
Line 2,038: | Line 2,555: | ||
Division by zero is not allowed. |
Division by zero is not allowed. |
||
-1.75 |
-1.75 |
||
</pre> |
|||
=={{header|Visual Basic .NET}}== |
|||
{{works with|Visual Basic .NET|9.0+}} |
|||
<syntaxhighlight lang="vbnet">Module DivByZeroDetection |
|||
Sub Main() |
|||
Console.WriteLine(safeDivision(10, 0)) |
|||
End Sub |
|||
Private Function safeDivision(v1 As Integer, v2 As Integer) As Boolean |
|||
Try |
|||
Dim answer = v1 / v2 |
|||
Return False |
|||
Catch ex As Exception |
|||
Return True |
|||
End Try |
|||
End Function |
|||
End Module |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
True |
|||
</pre> |
|||
=={{header|V (Vlang)}}== |
|||
<syntaxhighlight lang="Go"> |
|||
fn main() { |
|||
divide(0, 0) |
|||
divide(15, 0) |
|||
divide(15, 3) |
|||
} |
|||
fn divide(x f64, y f64) { |
|||
result := x/y |
|||
if result.str().contains_any_substr(["inf","nan"]) == true { |
|||
println("Can\'t divide by zero!") |
|||
return |
|||
} |
|||
println(result) |
|||
} |
|||
</syntaxhighlight> |
|||
Alternate version: |
|||
<syntaxhighlight lang="Go"> |
|||
fn main() { |
|||
divide(0, 0) |
|||
divide(15, 0) |
|||
divide(15, 3) |
|||
} |
|||
pub fn divide(x f64, y f64) { |
|||
succeed := divide_error_handler(x, y) or { |
|||
println(err) |
|||
return |
|||
} |
|||
println(succeed) |
|||
} |
|||
fn divide_error_handler(x f64, y f64) !f64 { |
|||
result := x/y |
|||
if result.str().contains_any_substr(["inf","nan"]) == true { |
|||
return error("Can\'t divide by zero!") |
|||
} |
|||
return result |
|||
} |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Can't divide by zero! |
|||
Can't divide by zero! |
|||
5.0 |
|||
</pre> |
|||
=={{header|Wren}}== |
|||
<syntaxhighlight lang="wren">var checkDivByZero = Fn.new { |a, b| |
|||
var c = a / b |
|||
if (c.isInfinity || c.isNan) return true |
|||
return false |
|||
} |
|||
System.print("Division by zero?") |
|||
System.print(" 0 / 0 -> %(checkDivByZero.call(0, 0))") |
|||
System.print(" 1 / 0 -> %(checkDivByZero.call(1, 0))") |
|||
System.print(" 1 / 1 -> %(checkDivByZero.call(1, 1))")</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Division by zero? |
|||
0 / 0 -> true |
|||
1 / 0 -> true |
|||
1 / 1 -> false |
|||
</pre> |
</pre> |
||
Line 2,048: | Line 2,660: | ||
zero". |
zero". |
||
< |
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; |
||
int A, B; |
int A, B; |
||
[Trap(false); \turn off error trapping |
[Trap(false); \turn off error trapping |
||
B:= 1234/(A-A); \(error not detected at compile time) |
B:= 1234/(A-A); \(error not detected at compile time) |
||
if GetErr then Text(0, "Divide by zero"); |
if GetErr then Text(0, "Divide by zero"); |
||
]</ |
]</syntaxhighlight> |
||
=={{header|Yorick}}== |
=={{header|Yorick}}== |
||
< |
<syntaxhighlight lang="yorick">func div_check(x, y) { |
||
if(catch(0x01)) |
if(catch(0x01)) |
||
return 1; |
return 1; |
||
temp = x/y; |
temp = x/y; |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
< |
<syntaxhighlight lang="zkl">fcn f(x,y){try{x/y}catch(MathError){println(__exception)}}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,073: | Line 2,685: | ||
MathError(INF (number is infinite)) |
MathError(INF (number is infinite)) |
||
</pre> |
</pre> |
||
{{omit from|6502 Assembly|No hardware division}} |
|||
{{omit from|8080 Assembly|No hardware division}} |
|||
{{omit from|ACL2}} |
{{omit from|ACL2}} |
||
{{omit from|AWK|Division by zero is always a fatal error.}} |
{{omit from|AWK|Division by zero is always a fatal error.}} |
||
Line 2,079: | Line 2,692: | ||
{{omit from|CMake|math(EXPR q "1/0") raises SIGFPE; CMake crashes and dumps core.}} |
{{omit from|CMake|math(EXPR q "1/0") raises SIGFPE; CMake crashes and dumps core.}} |
||
{{omit from|dc|Division by zero causes a warning message, but the program cannot detect this.}} |
{{omit from|dc|Division by zero causes a warning message, but the program cannot detect this.}} |
||
{{omit from|MIPS Assembly|Depends on the CPU version, but at some level the CPU has to check.}} |
|||
{{omit from|Retro|Divide by Zero is handled by the VM and is not exposed to the language}} |
{{omit from|Retro|Divide by Zero is handled by the VM and is not exposed to the language}} |
||
{{omit from|sed|No division.}} |
{{omit from|sed|No division.}} |
||
{{omit from|Swift|Division by zero is always a fatal error}} |
{{omit from|Swift|Division by zero is always a fatal error}} |
||
{{omit from|Z80 Assembly|No hardware division}} |
Latest revision as of 09:28, 18 June 2024
You are encouraged to solve this task according to the task description, using any language you may know.
- Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
68000 Assembly
The DIVU
and DIVS
opcodes will automatically trigger a system call to Trap #5 if division by zero occurs.
8th
Division by zero results in the value "Inf":
1 0 n:/ Inf? . cr
- Output:
true
ABAP
report zdiv_zero
data x type i.
try.
x = 1 / 0.
catch CX_SY_ZERODIVIDE.
write 'Divide by zero.'.
endtry.
Ada
-- Divide By Zero Detection
with Ada.Text_Io; use Ada.Text_Io;
with Ada.Float_Text_Io; use Ada.Float_Text_Io;
with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;
procedure Divide_By_Zero is
Fnum : Float := 1.0;
Fdenom : Float := 0.0;
Fresult : Float;
Inum : Integer := 1;
Idenom : Integer := 0;
Iresult : Integer;
begin
begin
Put("Integer divide by zero: ");
Iresult := Inum / Idenom;
Put(Item => Iresult);
exception
when Constraint_Error =>
Put("Division by zero detected.");
end;
New_Line;
Put("Floating point divide by zero: ");
Fresult := Fnum / Fdenom;
if Fresult > Float'Last or Fresult < Float'First then
Put("Division by zero detected (infinite value).");
else
Put(Item => Fresult, Aft => 9, Exp => 0);
end if;
New_Line;
end Divide_By_Zero;
- Output:
Integer divide by zero: Division by zero detected. Floating point divide by zero: Division by zero detected (infinite value).
Aime
integer
divide(integer n, integer d)
{
return n / d;
}
integer
can_divide(integer n, integer d)
{
return !trap(divide, n, d);
}
integer
main(void)
{
if (!can_divide(9, 0)) {
o_text("Division by zero.\n");
}
return 0;
}
- Output:
Division by zero.
The Aime interpreter reports execution errors by default, printing on standard error:
aime: can_divide: 4: division by zero
ALGOL 68
The USSR's ALGOL 68 had a "GOST 27975-88 Programming language ALGOL 68 extended (Язык программирования АЛГОЛ 68 расширенный)" that included additional keywords on, exception, raise. This was an extension, and probably made only an appearance in the Leningrad compiler (Алгола 68 Ленинград).
The following code sample implements zero division, without using language extensions or access to hardware interrupts.
PROC raise exception= ([]STRING args)VOID: (
put(stand error, ("Exception: ",args, newline));
stop
);
PROC raise zero division error := VOID:
raise exception("integer division or modulo by zero");
PROC int div = (INT a,b)REAL: a/b;
PROC int over = (INT a,b)INT: a%b;
PROC int mod = (INT a,b)INT: a%*b;
BEGIN
OP / = (INT a,b)REAL: ( b = 0 | raise zero division error; SKIP | int div (a,b) );
OP % = (INT a,b)INT: ( b = 0 | raise zero division error; SKIP | int over(a,b) );
OP %* = (INT a,b)INT: ( b = 0 | raise zero division error; SKIP | int mod (a,b) );
PROC a different handler = VOID: (
put(stand error,("caught division by zero",new line));
stop
);
INT x:=1, y:=0;
raise zero division error := a different handler;
print(x/y)
END
- Output:
caught division by zero
ALGOL W
Algol W allows the program to handle a number of system defined exceptions including INTDIVZERO and DIVZERO - integer and real division by zero.
A count of the number of times the exception is allowed is decremented each time the exception occurs. If this reaches 0, the program crashes. If it is greater than 0, the program continues and XCPNOTED(exception) returns true. This example uses this to detect integer and real division by 0. The INTDIVERO exception also occurs if the remainder (modulo) operator is used with 0.
begin
% integer division procedure %
% sets c to a divided by b, returns true if the division was OK, %
% false if there was division by zero %
logical procedure divideI ( integer value a, b; integer result c ) ;
begin
% set exception handling to allow integer division by zero to occur once %
INTDIVZERO := EXCEPTION( false, 1, 0, false, "INTDIVZERO" );
c := a div b;
not XCPNOTED(INTDIVZERO)
end divideI ;
% real division procedure %
% sets c to a divided by b, returns true if the division was OK, %
% false if there was division by zero %
logical procedure divideR ( long real value a, b; long real result c ) ;
begin
% set exception handling to allow realdivision by zero to occur once %
DIVZERO := EXCEPTION( false, 1, 0, false, "DIVZERO" );
c := a / b;
not XCPNOTED(DIVZERO)
end divideR ;
integer c;
real d;
write( divideI( 4, 2, c ) ); % prints false as no exception %
write( divideI( 5, 0, c ) ); % prints true as division by zero was detected %
write( divideR( 4, 2, d ) ); % prints false as no exception %
write( divideR( 5, 0, d ) ) % prints true as division by zero was detected %
end.
Arturo
try? -> 3/0
else -> print "division by zero"
- Output:
division by zero
AutoHotkey
ZeroDiv(num1, num2) {
If ((num1/num2) != "")
MsgBox % num1/num2
Else
MsgBox, 48, Warning, The result is not valid (Divide By Zero).
}
ZeroDiv(0, 3) ; is ok
ZeroDiv(3, 0) ; divize by zero alert
BASIC
Applesoft BASIC
The error code for division by zero is 133. There is a good overview of Applesoft ONERR GOTO handling here: https://web.archive.org/web/20190202133738/http://newsgroups.derkeiler.com/Archive/Comp/comp.sys.apple2.programmer/2010-04/msg00000.html
100 REM TRY
110 ONERR GOTO 200
120 D = - 44 / 0
190 END
200 REM CATCH
210 E = PEEK (222) < > 133
220 POKE 216,0: REM ONERR OFF
230 IF E THEN RESUME
240 CALL - 3288: REM RECOVER
250 PRINT "DIVISION BY ZERO"
BASIC256
onerror TratoError
print 2 / 3
print 3 / 5
print 4 / 0
end
TratoError:
print "Error in the line " + lasterrorline + " – Error number: " + lasterror + " – " + lasterrormessage + " (" + lasterrorextra + ")"
return
BBC BASIC
PROCdivide(-44, 0)
PROCdivide(-44, 5)
PROCdivide(0, 5)
PROCdivide(5, 0)
END
DEF PROCdivide(numerator, denominator)
ON ERROR LOCAL IF FALSE THEN
REM 'Try' clause:
PRINT numerator / denominator
ELSE
REM 'Catch' clause:
CASE ERR OF
WHEN 18: PRINT "Division by zero"
WHEN 20: PRINT "Number too big"
OTHERWISE RESTORE LOCAL : ERROR ERR, REPORT$
ENDCASE
ENDIF
ENDPROC
GW-BASIC
The Locomotive BASIC solution works without any changes.
IS-BASIC
100 WHEN EXCEPTION USE ERROR
110 FOR I=5 TO-2 STEP-1
120 PRINT 10/I
130 NEXT
140 END WHEN
150 HANDLER ERROR
160 IF EXTYPE=3001 THEN PRINT EXSTRING$(EXTYPE);" in line";EXLINE
170 CONTINUE
180 END HANDLER
Liberty BASIC
result = DetectDividebyZero(1, 0)
Function DetectDividebyZero(a, b)
On Error GoTo [Error]
DetectDividebyZero= (a/ b)
Exit Function
[Error]
If Err = 11 Then '11 is the error number raised when divide by zero occurs
Notice "Divide by Zero Detected!"
End If
End Function
Locomotive Basic
10 ON ERROR GOTO 60
20 PRINT 2/3
30 PRINT 3/5
40 PRINT 4/0
50 END
60 IF ERR=11 THEN PRINT "Division by zero in line"ERL:RESUME 50
- Output:
0.666666667 0.6 Division by zero in line 40
MSX Basic
The Locomotive BASIC solution works without any changes.
PureBasic
PureBasic can be compiled with the OnError library included which gives a way to track program errors without losing speed, doing so gives support for the following functions;
- ErrorAddress()
- ErrorCode()
- ErrorFile()
- ErrorLine()
- ErrorMessage()
- ErrorRegister()
- ErrorTargetAddress()
- ExamineAssembly()
- InstructionAddress()
- InstructionString()
- NextInstruction()
- OnErrorCall()
- OnErrorDefault()
- OnErrorExit()
- OnErrorGoto()
- RaiseError()
This way the final version of a program can still intercept program errors and provide some function, or information about the error to the user so he can report it back to the developer.
With Integers & OnError Library
;Set up a Procedure to handle any Error
Procedure MyErrorHandler()
Define txt$="The following error happened."+#CRLF$+ ErrorMessage()+"at line "+Str(ErrorLine())
MessageRequester("OnError test", txt$)
EndProcedure
; Tell where to go if an Error happens
OnErrorCall(@MyErrorHandler())
;Now, do something very stupid so that we may see an Error...
Repeat
A=Random(100)/Random(100)
ForEver
With Floats, and without OnError library
Define.d a, b
Debug a/b
Results in; -1.#IND
QBasic
ON ERROR GOTO TratoError
PRINT 2 / 3
PRINT 3 / 5
PRINT 4 / 0
END
TratoError:
PRINT "Error"; ERR; "in the line"; ERL
IF ERR = 11 THEN PRINT "Division by zero in line"; ERL: RESUME NEXT
Run BASIC
on error goto [error]
a = 1 / 0
wait
[error] ' error 11 is division by zero err number
If err = 11 Then print "Division by Zero"
wait
SmallBASIC
try
a = 1/0
catch error
print error
a = nil
end try
print a
TI-89 BASIC
1/0 = undef
is true.
True BASIC
WHEN error in
PRINT 2 / 3
PRINT 3 / 5
PRINT 4 / 0
USE
PRINT "Error "; EXTYPE; "in the line"; EXLINE
PRINT EXTEXT$
END WHEN
END
Batch File
@echo off
set /a dummy=5/0 2>nul
if %errorlevel%==1073750993 echo I caught a division by zero operation...
exit /b 0
BQN
Division of a non-zero number by zero results in infinity, a predefined symbol in BQN.
In CBQN and mlochbaum/BQN, 0 divided by 0 results in NaN
(not a number), so we can test these two cases to find out a division by zero error, provided the numerator isn't ∞
or NaN
to start with.
Div ← {∨´"∞"‿"NaN"≡¨<•Fmt𝕩}◶⊢‿"Division by 0"÷
•Show 5 Div 0
•Show 5 Div 5
•Show 0 Div 0
"Division by 0"
1
"Division by 0"
C
Technically, under the C standard, division by zero (regardless of type) is undefined behavior, so there is no standard way to run the division and then try to "detect" it later.
- The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined.
- -- C99 standard, section 6.5.5 paragraph 5
Some systems will raise SIGFPE if a program divides by zero.
#include <limits.h> /* INT_MIN */
#include <setjmp.h> /* siglongjmp(), sigsetjmp() */
#include <stdio.h> /* perror(), printf() */
#include <stdlib.h> /* exit() */
#include <signal.h> /* sigaction(), sigemptyset() */
static sigjmp_buf fpe_env;
/*
* This SIGFPE handler jumps to fpe_env.
*
* A SIGFPE handler must not return, because the program might retry
* the division, which might cause an infinite loop. The only safe
* options are to _exit() the program or to siglongjmp() out.
*/
static void
fpe_handler(int signal, siginfo_t *w, void *a)
{
siglongjmp(fpe_env, w->si_code);
/* NOTREACHED */
}
/*
* Try to do x / y, but catch attempts to divide by zero.
*/
void
try_division(int x, int y)
{
struct sigaction act, old;
int code;
/*
* The result must be volatile, else C compiler might delay
* division until after sigaction() restores old handler.
*/
volatile int result;
/*
* Save fpe_env so that fpe_handler() can jump back here.
* sigsetjmp() returns zero.
*/
code = sigsetjmp(fpe_env, 1);
if (code == 0) {
/* Install fpe_handler() to trap SIGFPE. */
act.sa_sigaction = fpe_handler;
sigemptyset(&act.sa_mask);
act.sa_flags = SA_SIGINFO;
if (sigaction(SIGFPE, &act, &old) < 0) {
perror("sigaction");
exit(1);
}
/* Do division. */
result = x / y;
/*
* Restore old hander, so that SIGFPE cannot jump out
* of a call to printf(), which might cause trouble.
*/
if (sigaction(SIGFPE, &old, NULL) < 0) {
perror("sigaction");
exit(1);
}
printf("%d / %d is %d\n", x, y, result);
} else {
/*
* We caught SIGFPE. Our fpe_handler() jumped to our
* sigsetjmp() and passes a nonzero code.
*
* But first, restore old handler.
*/
if (sigaction(SIGFPE, &old, NULL) < 0) {
perror("sigaction");
exit(1);
}
/* FPE_FLTDIV should never happen with integers. */
switch (code) {
case FPE_INTDIV: /* integer division by zero */
case FPE_FLTDIV: /* float division by zero */
printf("%d / %d: caught division by zero!\n", x, y);
break;
default:
printf("%d / %d: caught mysterious error!\n", x, y);
break;
}
}
}
/* Try some division. */
int
main()
{
try_division(-44, 0);
try_division(-44, 5);
try_division(0, 5);
try_division(0, 0);
try_division(INT_MIN, -1);
return 0;
}
- Output:
using OpenBSD/amd64
-44 / 0: caught division by zero! -44 / 5 is -8 0 / 5 is 0 0 / 0: caught division by zero! -2147483648 / -1: caught division by zero!
The last line is a mistake: the system confused an overflow (INT_MIN / -1 would be INT_MAX + 1) with division by zero and raised SIGFPE. The system normally ignores overflow.
C#
The floating point types (float, double) don't raise an exception, but return the values Infinity or NaN as appropriate.
using System;
namespace RosettaCode {
class Program {
static void Main(string[] args) {
int x = 1;
int y = 0;
try {
int z = x / y;
} catch (DivideByZeroException e) {
Console.WriteLine(e);
}
}
}
}
C++
#include<iostream>
#include<csignal> /* for signal */
#include<cstdlib>
using namespace std;
void fpe_handler(int signal)
{
cerr << "Floating Point Exception: division by zero" << endl;
exit(signal);
}
int main()
{
// Register floating-point exception handler.
signal(SIGFPE, fpe_handler);
int a = 1;
int b = 0;
cout << a/b << endl;
return 0;
}
Ceylon
shared void run() {
//integers divided by zero throw an exception
try {
value a = 1 / 0;
} catch (Exception e) {
e.printStackTrace();
}
//floats divided by zero produce infinity
print(1.0 / 0 == infinity then "division by zero!" else "not division by zero!");
}
Clojure
After catching the ArithmeticException, print the error message, and then try and recover by returning some meaningful value. In this case, if x > 0, return +inf, if 0, NaN, otherwise -inf.
(defn safe-/ [x y]
(try (/ x y)
(catch ArithmeticException _
(println "Division by zero caught!")
(cond (> x 0) Double/POSITIVE_INFINITY
(zero? x) Double/NaN
:else Double/NEGATIVE_INFINITY) )))
CLU
% This will catch a divide-by-zero exception and
% return a oneof instead, with either the result or div_by_zero.
% Overflow and underflow are resignaled.
check_div = proc [T: type] (a, b: T) returns (otype)
signals (overflow, underflow)
where T has div: proctype (T,T) returns (T)
signals (zero_divide, overflow, underflow)
otype = oneof[div_by_zero: null, result: T]
return(otype$make_result(a/b))
except when zero_divide:
return(otype$make_div_by_zero(nil))
end resignal overflow, underflow
end check_div
% Try it
start_up = proc ()
pair = struct[n, d: int]
pairs: sequence[pair] := sequence[pair]$[
pair${n: 10, d: 2}, % OK
pair${n: 10, d: 0}, % divide by zero
pair${n: 20, d: 2} % another OK one to show the program doesn't stop
]
po: stream := stream$primary_output()
for p: pair in sequence[pair]$elements(pairs) do
stream$puts(po, int$unparse(p.n) || "/" || int$unparse(p.d) || " = ")
tagcase check_div[int](p.n, p.d)
tag div_by_zero: stream$putl(po, "divide by zero")
tag result (r: int): stream$putl(po, int$unparse(r))
end
end
end start_up
- Output:
10/2 = 5 10/0 = divide by zero 20/2 = 10
COBOL
DIVIDE foo BY bar GIVING foobar
ON SIZE ERROR
DISPLAY "Division by zero detected!"
END-DIVIDE
Common Lisp
(handler-case (/ x y)
(division-by-zero () (format t "division by zero caught!~%")))
D
import std.stdio, std.string, std.math, std.traits;
string divCheck(T)(in T numer, in T denom)
if (isIntegral!T || isFloatingPoint!T) {
Unqual!(typeof(numer / denom)) result;
string msg;
static if (isIntegral!T) {
try {
result = numer / denom;
} catch(Error e) {
msg = "| " ~ e.msg ~ " (by Error)";
result = T.max;
}
} else { // Floating Point Type.
result = numer / denom;
if (numer.isNormal && result.isInfinity) {
msg = "| Division by Zero";
} else if (result != 0 && !result.isNormal) {
if (numer.isNaN)
msg = "| NaN numerator";
else if (denom.isNaN)
msg = "| NaN denominator";
else if (numer.isInfinity)
msg = "| Inf numerator";
else
msg = "| NaN (Zero Division by Zero)";
}
}
return format("%5s %s", format("%1.1g", real(result)), msg);
}
void main() {
writeln("Division with check:");
writefln("int 1/ 0: %s", divCheck(1, 0));
writefln("ubyte 1/ 0: %s", divCheck(ubyte(1), ubyte(0)));
writefln("real 1/ 0: %s", divCheck(1.0L, 0.0L));
writefln("real -1/ 0: %s", divCheck(-1.0L, 0.0L));
writefln("real 0/ 0: %s", divCheck(0.0L, 0.0L));
writeln;
writefln("real -4/-2: %s", divCheck(-4.0L,-2.0L));
writefln("real 2/-inf: %s", divCheck(2.0L, -real.infinity));
writeln;
writefln("real -inf/-2: %s", divCheck(-real.infinity, -2.0L));
writefln("real +inf/-2: %s", divCheck(real.infinity, -2.0L));
writefln("real nan/-2: %s", divCheck(real.nan, -2.0L));
writefln("real -2/ nan: %s", divCheck(-2.0L, real.nan));
writefln("real nan/ 0: %s", divCheck(real.nan, 0.0L));
writefln("real inf/ inf: %s",
divCheck(real.infinity, real.infinity));
writefln("real nan/ nan: %s", divCheck(real.nan, real.nan));
}
- Output:
Division with check: int 1/ 0: 2e+09 | Integer Divide by Zero (by Error) ubyte 1/ 0: 3e+02 | Integer Divide by Zero (by Error) real 1/ 0: inf | Division by Zero real -1/ 0: -inf | Division by Zero real 0/ 0: -nan | NaN (Zero Division by Zero) real -4/-2: 2 real 2/-inf: -0 real -inf/-2: inf | Inf numerator real +inf/-2: -inf | Inf numerator real nan/-2: nan | NaN numerator real -2/ nan: nan | NaN denominator real nan/ 0: nan | NaN numerator real inf/ inf: -nan | Inf numerator real nan/ nan: nan | NaN numerator
Delphi
program DivideByZero;
{$APPTYPE CONSOLE}
uses SysUtils;
var
a, b: Integer;
begin
a := 1;
b := 0;
try
WriteLn(a / b);
except
on e: EZeroDivide do
Writeln(e.Message);
end;
end.
Déjà Vu
divcheck x y:
true
try:
drop / x y
catch value-error:
not
if divcheck 1 0:
!print "Okay"
else:
!print "Division by zero"
- Output:
Division by zero
E
def divide(numerator, denominator) {
def floatQuotient := numerator / denominator
if (floatQuotient.isNaN() || floatQuotient.isInfinite()) {
return ["zero denominator"]
} else {
return ["ok", floatQuotient]
}
}
EasyLang
func checkDivZero a b .
r = a / b
if r = number "nan" or r = number "inf" or r = number "-inf"
return 1
.
.
print checkDivZero 5 7
print checkDivZero -1 0
ECL
Division by zero defaults to generating a zero result (0), rather than reporting a "divide by zero" error. This avoids invalid or unexpected data aborting a long job. The default behavior can be changed using #OPTION.
Evaluate to zero - default behavior
DBZ(REAL8 Dividend,INTEGER8 Divisor) := Quotient/Divisor;
#option ('divideByZero', 'zero');
DBZ(10,0); //returns 0.0
Stop and report a division by zero error:
DBZ(REAL8 Dividend,INTEGER8 Divisor) := Quotient/Divisor;
#option ('divideByZero', 'fail');
DBZ(10,0); //returns error message "Error: System error: -1: Division by zero (0, 0), -1,"
Returns "nan":
DBZ(REAL8 Dividend,INTEGER8 Divisor) := Quotient/Divisor;
#option ('divideByZero', 'nan');
DBZ(10,0); //returns 'nan'
/* NOTE: This is only currently supported for real numbers. Division by zero creates a quiet NaN,
which will propogate through any real expressions it is used in.
You can use NOT ISVALID(x) to test if the value is a NaN.
Integer and decimal division by zero continue to return 0.
*/
Eiffel
version 2.4
In a file called main.e:
class MAIN
creation main
feature main is
local
x, y: INTEGER;
retried: BOOLEAN;
do
x := 42;
y := 0;
if not retried then
io.put_real(x / y);
else
print("NaN%N");
end
rescue
print("Caught division by zero!%N");
retried := True;
retry
end
end
Note: The "rescue" statement catches every exception.
Ela
open core number
x /. y = try Some (x `div` y) with
_ = None
(12 /. 2, 12 /. 0)
Output:
(Some 6, None)
Of course the cleanest way to implement the safe division function is through pattern matching:
x /. 0 = None
x /. y = Some (x / y)
But it doesn't satisfy the task.
Elixir
defmodule Division do
def by_zero?(x,y) do
try do
_ = x / y
false
rescue
ArithmeticError -> true
end
end
end
[{2, 3}, {3, 0}, {0, 5}, {0, 0}, {2.0, 3.0}, {3.0, 0.0}, {0.0, 5.0}, {0.0, 0.0}]
|> Enum.each(fn {x,y} ->
IO.puts "#{x} / #{y}\tdivision by zero #{Division.by_zero?(x,y)}"
end)
- Output:
2 / 3 division by zero false 3 / 0 division by zero true 0 / 5 division by zero false 0 / 0 division by zero true 2.0 / 3.0 division by zero false 3.0 / 0.0 division by zero true 0.0 / 5.0 division by zero false 0.0 / 0.0 division by zero true
Emacs Lisp
Division by zero gives an error of type arith-error
which can be caught in the usual ways with condition-case
and similar. A division by zero example can be found in the Elisp manual section "Handling Errors".
(condition-case nil
(/ 1 0)
(arith-error
(message "Divide by zero (either integer or float)")))
Erlang
div_check(X,Y) ->
case catch X/Y of
{'EXIT',_} -> true;
_ -> false
end.
ERRE
PROGRAM DIV_BY_ZERO
EXCEPTION
IF ERR=11 THEN PRINT("Division by Zero") END IF
END EXCEPTION
BEGIN
PRINT(0/3)
PRINT(3/0)
END PROGRAM
EXCEPTION (when it's present) detects runtime errors, otherwise program stops with a [Runtime error #nn] where nn is the error code. Error codes are different between C-64 and PC version.
- Output:
0 Division by zero
F#
let detectDivideZero (x : int) (y : int):int option =
try
Some(x / y)
with
| :? System.ArithmeticException -> None
printfn "12 divided by 3 is %A" (detectDivideZero 12 3)
printfn "1 divided by 0 is %A" (detectDivideZero 1 0)
Output:
12 divided by 3 is Some 4 1 divided by 0 is null
Factor
USE: math.floats.env
: try-div ( a b -- )
'[ { +fp-zero-divide+ } [ _ _ /f . ] with-fp-traps ] try ;
( scratchpad ) 1 2 try-div 0.5 ( scratchpad ) 1 0 try-div Floating point trap Type :help for debugging help.
Fancy
def divide: x by: y {
try {
x / y
} catch DivisionByZeroError => e {
e message println # prints error message
}
}
Forth
: safe-/ ( x y -- x/y )
['] / catch -55 = if cr ." divide by zero!" 2drop 0 then ;
Fortran
Fortran has only floating-point exception handling. Integer exceptions are missing in ISO standard. Gfortran detects some integer explicit exceptions during compilation and is able to generate some run-time checks for integer overflow (with -ftrapv). Intel ifort does not have integer overflow / division by zero detection.
Floating-point division by zero detection.
program rosetta_divbyzero
implicit none
integer, parameter :: rdp = kind(1.d0)
real(rdp) :: normal,zero
normal = 1.d0
zero = 0.d0
call div_by_zero_check(normal,zero)
contains
subroutine div_by_zero_check(x,y)
use, intrinsic :: ieee_exceptions
use, intrinsic :: ieee_arithmetic
implicit none
real(rdp), intent(in) :: x,y
real(rdp) :: check
type(ieee_status_type) :: status_value
logical :: flag
flag = .false.
! Get the flags
call ieee_get_status(status_value)
! Set the flags quiet
call ieee_set_flag(ieee_divide_by_zero,.false.)
write(*,*)"Inf supported? ",ieee_support_inf(check)
! Calculation involving exception handling
check = x/y
write(*,*)"Is check finite?",ieee_is_finite(check), check
call ieee_get_flag(ieee_divide_by_zero, flag)
if (flag) write(*,*)"Warning! Division by zero detected"
! Restore the flags
call ieee_set_status(status_value)
end subroutine div_by_zero_check
end program rosetta_divbyzero
Integer division by zero. No detection.
program rosetta_integer_divbyzero
implicit none
integer :: normal,zero,answer
normal = 1
zero = 0
answer = normal/ zero
write(*,*) answer
end program rosetta_integer_divbyzero
FreeBASIC
In FreeBASIC integer division by zero is a fatal error and cannot be caught by the language's built-in error handling constructs.
However, it is possible to detect such an error by using floating point division instead and relying on the fact that when Infinity, -Infinity and NaN are converted back to a 4 or 8 byte signed integer, the result is the lower bound of the range of the relevant integer type.
For Win64, an Integer is a signed 8 byte type and the returned value is therefore -9223372036854775808 which would be unlikely to arise in any other integer division scenario.
The following code relies on this 'hack':-
' FB 1.05.0 Win64
Const divByZeroResult As Integer = -9223372036854775808
Sub CheckForDivByZero(result As Integer)
If result = divByZeroResult Then
Print "Division by Zero"
Else
Print "Division by Non-Zero"
End If
End Sub
Dim As Integer x, y
x = 0 : y = 0
CheckForDivByZero(x/y) ' automatic conversion to type of parameter which is Integer
x = 1
CheckForDivByZero(x/y)
x = -1
CheckForDivByZero(x/y)
y = 1
CheckForDivByZero(x/y)
Print
Print "Press any key to exit"
Sleep
- Output:
Division by Zero Division by Zero Division by Zero Division by Non-Zero
FutureBasic
Stop on error. Error type reported in log console.
on error stop
long a
print a / 0
HandleEvents
Gambas
Click this link to run this code
Public Sub Main()
Try Print 1 / 0
If Error Then Print Error.Text
End
Output:
Division by zero
Go
Detection on integers by recovering from a panic:
package main
import "fmt"
func divCheck(x, y int) (q int, ok bool) {
defer func() {
recover()
}()
q = x / y
return q, true
}
func main() {
fmt.Println(divCheck(3, 2))
fmt.Println(divCheck(3, 0))
}
Output:
1 true 0 false
Groovy
In Groovy, the float and double types follow IEEE numeric formats and rules. Here is a solution for double:
def dividesByZero = { double n, double d ->
assert ! n.infinite : 'Algorithm fails if the numerator is already infinite.'
(n/d).infinite || (n/d).naN
}
Test program:
((3d)..(0d)).each { i ->
((2d)..(0d)).each { j ->
println "${i}/${j} divides by zero? " + dividesByZero(i,j)
}
}
Output:
3.0/2.0 divides by zero? false 3.0/1.0 divides by zero? false 3.0/0.0 divides by zero? true 2.0/2.0 divides by zero? false 2.0/1.0 divides by zero? false 2.0/0.0 divides by zero? true 1.0/2.0 divides by zero? false 1.0/1.0 divides by zero? false 1.0/0.0 divides by zero? true 0.0/2.0 divides by zero? false 0.0/1.0 divides by zero? false 0.0/0.0 divides by zero? true
Haskell
import qualified Control.Exception as C
check x y = C.catch (x `div` y `seq` return False)
(\_ -> return True)
hexiscript
let a 1
let b 0
if tostr (a / (b + 0.)) = "inf"
println "Divide by Zero"
else
println a / b
endif
HicEst
FUNCTION zero_divide(num, denom)
XEQ( num// "/" // denom, *99) ! on error jump to label 99
zero_divide = 0 ! division OK
RETURN
99 zero_divide = 1
END
zero_divide(0, 1) returns 0 (false)
zero_divide( 1, 3-2-1 ) returns 1 (true)
HolyC
HolyC throws Except:DivZero
.
try {
Print("%d\n", 10 / 0);
} catch {
Print("Divide by zero");
}
i
//Division by zero is defined in 'i' so the result can be checked to determine division by zero.
concept IsDivisionByZero(a, b) {
c = a/b
if c = 0 and a - 0 or a = 0 and c > 0
print( a, "/", b, " is a division by zero.")
return
end
print( a, "/", b, " is not division by zero.")
}
software {
IsDivisionByZero(5, 0)
IsDivisionByZero(5, 2)
IsDivisionByZero(0, 0)
}
Icon and Unicon
Setting &error to a non-zero number traps errors and converts then to failures. Division by zero generates error 201
Sample Output:
Run-time error 201 : division by zero in line #3 - converted to failure
IDL
if not finite( <i>expression</i> ) then ...
J
Generally, this task should be accomplished in J using 0=DEN. Here we take an approach that's more comparable with the other examples on this page.
Divide by zero is not an error in J. It results in infinity which is represented by an underscore ( _
) or negative infinity (represented by a double underescore) or complex values which can have infinities for the real and/or imaginary part., except that 0 divided by 0 is defined to have the result zero (mathematically speaking any number is a valid result for 0 divided by 0, because 0 times any number is zero).
See also the J Dictionary page on infinity
So, anyways, the task:
funnydiv=: 0 { [: (,:'division by zero detected')"_^:(_ e. |@,) (,>:)@:(,:^:(0<#@$))@[ %"_1 _ ]
This performs division and instead of returning the result returns the string 'division by zero detected' if a denominator was zero. Note that it also provides this result if a numerator was infinite, regardless of the denominator, but since there's no reasonable use for this implementation that's probably not a problem.
Examples:
3 funnydiv 2
1.5
3 funnydiv 0
division by zero detected
0 funnydiv 0
division by zero detected
0 funnydiv 3
0
2 3 4 funnydiv 5
0.4 0.6 0.8
Java
Two ways to accomplish this task are presented here. They each return true if there is a division by zero or if Double.POSITIVE_INFINITY is used as a numerator.
One way to do this check in Java is to use the isInfinite function from the Double class:
public static boolean infinity(double numer, double denom){
return Double.isInfinite(numer/denom);
}
Another way is to use the ArithmeticException as a check (which is not preferred because it expects an exception):
public static boolean except(double numer, double denom){
try{
int dummy = (int)numer / (int)denom;//ArithmeticException is only thrown from integer math
return false;
}catch(ArithmeticException e){return true;}
}
JavaScript
JavaScript does not give an error on division by 0, and this is more useful than it is Mathematically correct. However, 0 divided by 0 will yield NaN, which is actually correct, since 0/0 is defined as "indeterminate". It may be better to return 0 or false in these situations, though, depending on the application (in JavaScript, 0 and false are the same thing):
function divByZero(dividend,divisor)
{
var quotient=dividend/divisor;
if(isNaN(quotient)) return 0; //Can be changed to whatever is desired by the programmer to be 0, false, or Infinity
return quotient; //Will return Infinity or -Infinity in cases of, for example, 5/0 or -7/0 respectively
}
alert(divByZero(0,0));
This will output "0" instead of "NaN". In this case, when checking against for true, the condition needs to be explicit ("===" rather than "==") because if divByZero(5,5) is used, this will return 1, which is the same as true when using "==".
jq
jq 1.4, like JavaScript, does not raise an error on division by 0, but unlike JavaScript, the result of division by zero is a number: either -1.7976931348623157e+308 or 1.7976931348623157e+308.
We can however define div(x;y) so that it raises an error, "NaN", if y equals 0:
def div(x;y): if y==0 then error("NaN") else x/y end;
In versions of jq since 1.4, we can then catch the error, as illustrated by the following snippet:
try div(3;0) catch if "NaN" then "div by 0 error detected" else . end
Jsish
Like other ECMAScript implementations, Jsi does not error out on divide by zero. There is the internal representation of +Infinity, -Infinity and NaN. Detection of division by zero is not exact, other problems with the arithmetic can also set the state, but:
if (!isFinite(numerator/denominator)) puts("result is infinity or not a number");
Julia
Julia handles division by zero quite gracefully. The result depends upon the numerator: Inf
, -Inf
, NaN
or (for complex numbers) some mixture of these. This solution detects division by zero by checking for these sorts of values.
isdefinite(n::Number) = !isnan(n) && !isinf(n)
for n in (1, 1//1, 1.0, 1im, 0)
d = n / 0
println("Dividing $n by 0 ", isdefinite(d) ? "results in $d." : "yields an indefinite value ($d).")
end
- Output:
Divding 1 by 0 yields an indefinite value (Inf). Divding 1//1 by 0 yields an indefinite value (1//0). Divding 1.0 by 0 yields an indefinite value (Inf). Divding 0 + 1im by 0 yields an indefinite value (NaN + Inf*im). Divding 0 by 0 yields an indefinite value (NaN).
Kotlin
// version 1.1
fun divideByZero(x: Int, y:Int): Boolean =
try {
x / y
false
} catch(e: ArithmeticException) {
true
}
fun main(args: Array<String>) {
val x = 1
val y = 0
if (divideByZero(x, y)) {
println("Attempted to divide by zero")
} else {
@Suppress("DIVISION_BY_ZERO")
println("$x / $y = ${x / y}")
}
}
- Output:
Attempted to divide by zero
Lambdatalk
Thanks to Javascript a division by zero doesn't throw an error, just the word "Infinity".
{def DivByZero?
{lambda {:w}
{W.equal? :w Infinity}}}
{DivByZero? {/ 3 2}}
-> false
{DivByZero? {/ 3 0}}
-> true
LabVIEW
This image is a VI Snippet, an executable image of LabVIEW code. The LabVIEW version is shown on the top-right hand corner. You can download it, then drag-and-drop it onto the LabVIEW block diagram from a file browser, and it will appear as runnable, editable code.
If the division node receives zero on both nodes (0/0), the Result will be "NaN"
langur
val dz = fn(x, y) {
[x / y, true]
catch {
if _err'msg -> re/division by 0/ {
[0, false]
} else {
# rethrow the error if not division by 0
throw
}
}
}
writeln dz(3, 2)
writeln dz(3, 0)
- Output:
[1.5, true] [0, false]
Lasso
define dividehandler(a,b) => {
(
#a->isNotA(::integer) && #a->isNotA(::decimal) ||
#b->isNotA(::integer) && #b->isNotA(::decimal)
) ? return 'Error: Please supply all params as integers or decimals'
protect => {
handle_error => { return 'Error: Divide by zero' }
local(x = #a / #b)
return #x
}
}
dividehandler(1,0)
- Output:
Error: Divide by zero
Lingo
on div (a, b)
-- for simplicity type check of vars omitted
res = value("float(a)/b")
if voidP(res) then
_player.alert("Division by zero!")
else
return res
end if
end
Lua
Lua, like Javascript, does not error on DIVIDE-BY-ZERO, but returns infinity, -infinity or -nan. So:
local function div(a,b)
if b == 0 then error() end
return a/b
end
M2000 Interpreter
To place a division as argument for lazy evaluation we have to use lazy$() which make a proper anonymous function. So we get a() as a function in DetectDivisionByZero() and try to execute. So if we get the specific error we get true.
Lazy$() not only make a function but also pass the same scope to that function where we use it. So Variables A, B, Z which they are in scope in module Checkit, and not in Function DetectDivisionByZero(), they used by the lazy evaluation contraction. References in M2000 passed as weak references, and for functions passed as code in a string (for objects passed the weak reference of the object plus the code).
Print function("{Read x : =x**2}", 2)=4
For a fast way to check a valid expression we can use Valid()
Print Valid(100/0)=False
Module Checkit {
Function DetectDivisionByZero(&a()) {
Try {
a=a()
}
=Error$=" division by zero"
}
Print DetectDivisionByZero(lazy$(10/0))=True
Z=10
A=4
B=0
Print DetectDivisionByZero(lazy$(Z/B))=True
Print DetectDivisionByZero(lazy$(Z/A))=False
}
Checkit
M4
ifelse(eval(2/0),`',`detected divide by zero or some other error of some kind')
Output, with standard output labeled "==>" and error output labeled "error==>":
error==>divideby0.m4:1: m4: Divide by zero in eval: 2/0 ==>detected divide by zero or some other error of some kind
Maple
By default numeric exceptions raise errors which cannot be trapped by the usual try...catch
mechanism. Instead numeric exceptions may be controlled by custom handling procedures.
1/0; # Here is the default behavior.
Output:
Error, numeric exception: division by zero
Here is a simple custom handler being installed and used.
NumericEventHandler( ':-division_by_zero'
= proc() infinity; end proc ):
1/0;
NumericStatus(':-division_by_zero'); # We may check the status flag
Output:
infinity true
Alternatively, the custom handler could issue a warning or clear the status flag for that exception, as well as return some particular value.
NumericEventHandler( ':-division_by_zero'
= proc()
WARNING("division by zero");
NumericStatus(':-division_by_zero'=false):
infinity;
end proc ):
1/0;
NumericStatus(':-division_by_zero');
Output:
Warning, division by zero infinity false
Mathematica / Wolfram Language
Check[2/0, Print["division by 0"], Power::infy]
MATLAB
function [isDividedByZero] = dividebyzero(numerator, denomenator)
isDividedByZero = isinf( numerator/denomenator );
% If isDividedByZero equals 1, divide by zero occured.
Maxima
f(a, b) := block([q: errcatch(a / b)], if emptyp(q) then 'error else q[1]);
f(5, 6);
5 / 6
f(5, 0;)
'error
MAXScript
if not bit.isFinite (<i>expression</i>) then...
min
The following operator will detect division by zero since the result will be infinity.
(/ inf ==) :div-zero?
Integer divison (that is, div
and not /
) by zero will cause min to exit with an uncatchable arithmetic error.
MiniScript
number.isInfinite = function
return abs(self) == 1/0
end function
number.isNaN = function
return self != self
end function
number.toBoolStr = function
if self == 0 then return "false"
return "true"
end function
checkDivByZero = function(a, b)
c = a / b
if c.isInfinite or c.isNaN then return true
return false
end function
print "Division by zero?"
print " 0 / 0 -> " + checkDivByZero( 0, 0).toBoolStr
print " 1 / 0 -> " + checkDivByZero( 1, 0).toBoolStr
print " 1 / 1 -> " + checkDivByZero( 1, 1).toBoolStr
print " -5 / 0 -> " + checkDivByZero(-5, 0).toBoolStr
print " -5 / 2 -> " + checkDivByZero(-5, 2).toBoolStr
- Output:
Division by zero? 0 / 0 -> true 1 / 0 -> true 1 / 1 -> false -5 / 0 -> true -5 / 2 -> false
mIRC Scripting Language
var %n = $rand(0,1)
if ($calc(1/ %n) == $calc((1/ %n)+1)) {
echo -ag Divides By Zero
}
else {
echo -ag Does Not Divide By Zero
}
MUMPS
DIV(A,B) ;Divide A by B, and watch for division by zero
;The ANSI error code for division by zero is "M9".
;$ECODE errors are surrounded by commas when set.
NEW $ETRAP
SET $ETRAP="GOTO DIVFIX^ROSETTA"
SET D=(A/B)
SET $ETRAP=""
QUIT D
DIVFIX
IF $FIND($ECODE,",M9,")>1 WRITE !,"Error: Division by zero" SET $ECODE="" QUIT ""
QUIT "" ; Fall through for other errors
Output:
USER>W $$DIV^ROSETTA(1,2) .5 USER>W $$DIV^ROSETTA(1,4) .25 USER>W $$DIV^ROSETTA(1,0) Error: Division by zero USER>W $$DIV^ROSETTA(1,C) W $$DIV^ROSETTA(1,C) ^ <UNDEFINED> *C
Nanoquery
def div_check(x, y)
try
(x / y)
return false
catch
return true
end
end
Neko
Float, non-float as infinity and catching an $idiv. *Not demonstrated in a function.*
/**
Detect division by zero
*/
var ans = 1.0 / 0.0
if $isinfinite(ans) $print("division by zero: ", ans, "\n")
ans = 1 / 0
if $isinfinite(ans) $print("division by zero: ", ans, "\n")
try $print($idiv(1, 0)) catch problem $print("idiv by zero: ", problem, "\n")
- Output:
prompt$ nekoc divide-zero.neko prompt$ neko divide-zero.n division by zero: inf division by zero: inf idiv by zero: $idiv
NetLogo
;; Division by zero detection using CAREFULLY
;; The CAREFULLY clause exists in NetLogo since version 2.0
;; In prior versions of NetLogo, you must examine the divisor prior to performing the division.
;; The variables result, a, and b must all be previously created global, local, or agent -own'd variables.
;; NetLogo variables are dynamically typed, so we are assuming that a and b contain numbers.
;; (All numbers in NetLogo are double-precision floating-point numbers.)
;; However, even if not numbers, the result is still the same: the carefully clause will
;; supress the run-time error and run the "commands if error" block, setting result to false.
;; this false value can be detected, to alter the rest of the course of the code
;; This behavior is consistent with other NetLogo primitives, such as POSTIION, that report
;; FALSE, rather than a number, if the operation fails.
carefully
[ ;; commands to try to run
set result a / b
]
[ ;; commands to run if an error occurs in the previous block.
set result false
]
ifelse is-number? result
[ output-print (word a " / " b " = " result)
]
[ output-print (word a " / " b " is not calculable"
]
NetRexx
/* NetRexx */
options replace format comments java crossref symbols nobinary
method divide(dividend, divisor) public constant returns Rexx
do
quotient = dividend / divisor
catch exu = DivideException
exu.printStackTrace()
quotient = 'undefined'
catch exr = RuntimeException
exr.printStackTrace()
quotient = 'error'
end
return quotient
method main(args = String[]) public static
-- process input arguments and set sensible defaults
arg = Rexx(args)
parse arg dividend .',' divisor .
if dividend.length() = 0 then dividend = 1
if divisor.length() = 0 then divisor = 0
say dividend '/' divisor '=' divide(dividend, divisor)
return
Output:
netrexx.lang.DivideException: Divide by 0 at netrexx.lang.Rexx.dodivide(Rexx.nrx:1778) at netrexx.lang.Rexx.OpDiv(Rexx.nrx:1674) at zz.divide(zz.nrx:20) at zz.main(zz.nrx:47)
NewLISP
#! /usr/local/bin/newlisp
(define (check-division x y)
(catch (/ x y) 'check-zero)
(if (not (integer? check-zero))
(setq check-zero "Division by zero."))
check-zero
)
(println (check-division 10 4))
(println (check-division 4 0))
(println (check-division 20 5))
(println (check-division 11 0))
(exit)
Output:
2 Division by zero. 4 Division by zero.
Nim
In version 1.4 and later, Nim makes a distinction between errors and defects. The first ones are exceptions which can be caught using an except clause. The second ones are non “catchable” exceptions which cause the program to abort. In version 1.4, by default, defects can still be caught, but this behavior is likely to change in next versions. Note that the distinction between errors and defects allow to process defects much more efficiently than errors.
Division by zero is now a defect and DivByZeroError is deprecated and replaced by DivByZeroDefect. So, the following program which catches a DivByZeroDefect is likely to fail to compile or execute correctly in future versions (but it is also very likely that using option --panics:off
will restore the previous behavior).
In debug mode (the default), all checks are activated. In release mode (-d:release
), checks are also activated. In danger mode (-d:danger
) all checks are deactivated.
It is possible to declare the checks to activate or deactivate in some parts of code using a pragma, as in the following example.
{.push overflowChecks: on.}
proc divCheck(x, y): bool =
try:
discard x div y
except DivByZeroDefect:
return true
return false
{.pop.} # Restore default check settings
echo divCheck(2, 0)
NS-HUBASIC
10 ON ERROR GOTO 40
20 PRINT 1/0
30 END
40 IF ERR = 10 THEN PRINT "DIVISION BY ZERO IN LINE"ERL
50 RESUME 30
OCaml
Detection on integers by catching an exception:
let div_check x y =
try
ignore (x / y);
false
with Division_by_zero ->
true
Detection on floats by checking for infiniteness:
let div_check x y =
classify_float (x /. y) = FP_infinite
Octave
Dividing by zero raises a warning (a warning does not stop the execution), not an error (and the given answer is Infinity), so it's not possible to use a try-catch construct; we can however check for the lastwarn if the answer is Inf.
d = 5/0;
if ( isinf(d) )
if ( index(lastwarn(), "division by zero") > 0 )
error("division by zero")
endif
endif
Oforth
: divideCheck(n)
| e |
try: e [ 128 n / ] when: [ "Zero detected..." . ]
"Leaving" println ;
Ol
Division by inexact zero produces Infinity (`+inf.0` and `-inf.0`) values, but division by exact zero (like `(/ n 0)`) - produces runtime error!
(define (safediv a b)
(if (eq? (type b) type-complex)
(/ a b) ; complex can't be 0
(let ((z (/ 1 (inexact b))))
(unless (or (equal? z +inf.0) (equal? z -inf.0))
(/ a b)))))
; testing:
(for-each (lambda (x)
(if x (print x) (print "division by zero detected")))
(list
(safediv 1 5) ; => 1/5
(safediv 2 0) ; => division by zero detected
(safediv 3 1+2i) ; => 3/5-6/5i
(safediv 4 0+i) ; => 0-4i
(safediv 5 7/5) ; => 25/7
))
ooRexx
/* REXX **************************************************************
* program demonstrates detects and handles division by zero.
* translated from REXX:
* removed fancy error reporting (ooRexx does not support linesize)
* removed label Novalue (as novalue is not enabled there)
* 28.04.2013 Walter Pachl
*********************************************************************/
Signal on Syntax /*handle all REXX syntax errors. */
x = sourceline() /*being cute, x=size of this pgm.*/
y = x-x /*setting to zero the obtuse way.*/
z = x/y /* attempt to divide by 0 */
exit /* will not be reached */
Syntax:
Say 'Syntax raised in line' sigl
Say sourceline(sigl)
Say 'rc='rc '('errortext(rc)')'
Exit 12
Output:
Syntax raised in line 11 z = x/y /* attempt to divide by 0 */ rc=42 (Arithmetic overflow/underflow)
Oz
For integer division only.
try
{Show 42 div 0}
catch error(kernel(div0 ...) ...) then
{System.showInfo "Division by zero detected."}
end
PARI/GP
Pari/GP version 2.7 introduces iferr()
. The given err
variable is lexically bound in the recovery code and in the optional predicate (what to trap, default all errors). Error type e_INV
is division by zero.
iferr(1/0,
err,
print("division by 0"); print("or other non-invertible divisor"),
errname(err) == "e_INV");
Or the previous trap()
,
trap(,"division by 0",m/n)
Pascal
See Delphi
Perl
This function returns true iff its second argument is zero.
sub div_check
{local $@;
eval {$_[0] / $_[1]};
$@ and $@ =~ /division by zero/;}
Phix
try integer i = 1/0 catch e ?e[E_USER] end try puts(1,"still running...\n")
- Output:
"attempt to divide by 0" still running...
PHP
This function returns true iff its second argument is zero.
function div_check($x, $y) {
@trigger_error(''); // a dummy to detect when error didn't occur
@($x / $y);
$e = error_get_last();
return $e['message'] != '';
}
function div_check($x, $y) {
return @($x / $y) === FALSE; // works at least in PHP/5.2.6-3ubuntu4.5
}
PicoLisp
(catch '("Div/0") (/ A B))
PL/I
Proc DivideDZ(a,b) Returns(Float Bin(33));
Dcl (a,b,c) Float Bin(33);
On ZeroDivide GoTo MyError;
c=a/b;
Return(c);
MyError:
Put Skip List('Divide by Zero Detected!');
End DivideDZ;
xx=DivideDZ(1,0);
PL/SQL
FUNCTION divide(n1 IN NUMBER, n2 IN NUMBER)
RETURN BOOLEAN
IS
result NUMBER;
BEGIN
result := n1/n2;
RETURN(FALSE);
EXCEPTION
WHEN ZERO_DIVIDE THEN
RETURN(true);
end divide;
divide(0,1) --false
divide(1,0) --true, division by zero
Plain English
When dividing by zero in Plain English, it explicitly returns 2147483647. The decider below detects division by zero by checking if it returns 2147483647.
To run:
Start up.
If 1 and 0 does cause division error, write "Division by zero found" to the output.
Wait for the escape key.
Shut down.
To decide if a number and another number does cause division error:
Put the number divided by the other number into a third number.
If the third number is the largest number, say yes.
Say no.
PowerShell
function div ($a, $b) {
try{$a/$b}
catch{"Bad parameters: `$a = $a and `$b = $b"}
}
div 10 2
div 1 0
- Output:
5 Bad parameters: $a = 1 and $b = 0
Prolog
div(A, B, C, Ex) :-
catch((C is A/B), Ex, (C = infinity)).
- Output:
?- div(10, 5, X, Ex). X = 2. ?- div(1, 0, X, Ex). X = infinity, Ex = error(evaluation_error(zero_divisor), context((/)/2, _2950)).
Pure
Floating point division yields inf or nan values as appropriate (if the FPU supports IEEE 754):
> 1/0, -1/0, 0/0;
inf,-inf,nan
It's possible to check for these values as follows:
> inf_or_nan x = infp x || nanp x;
> map inf_or_nan [1/0, -1/0, 0/0];
[1,1,1]
In contrast, integer division by zero raises an exception which can be caught as follows:
> divide n m = catch (\_ -> "divide by 0") (n div m);
> divide 0 1;
0
> divide 1 0;
"divide by 0"
Python
def div_check(x, y):
try:
x / y
except ZeroDivisionError:
return True
else:
return False
Q
Division by zero does not raise an error, instead it results in an infinity (0w or -0w) or NaN (0n).
r:x%0
?[1=sum r=(0n;0w;-0w);"division by zero detected";()]
R
Division by zero does not raise an error nor a warning. Division of a non-zero value by zero returns infinity. Division of zero by zero returns NaN; Whether the result is not finite can be checked:
d <- 5/0
if ( !is.finite(d) ) {
# it is Inf, -Inf, or NaN
}
Racket
In Racket, the division by zero exception can be caught directly:
#lang racket
(with-handlers ([exn:fail:contract:divide-by-zero?
(λ (e) (displayln "Divided by zero"))])
(/ 1 0))
Raku
(formerly Perl 6)
Try/Catch
sub div($a, $b) {
my $r;
try {
$r = $a / $b;
CATCH {
default { note "Unexpected exception, $_" }
}
}
return $r // Nil;
}
say div(10,2);
say div(1, sin(0));
- Output:
5 Unexpected exception, Attempt to divide 1 by zero using / Nil
Multi Method Dispatch
multi div($a, $b) { return $a / $b }
multi div($a, $b where { $b == 0 }) { note 'Attempt to divide by zero.'; return Nil }
say div(10, 2);
say div(1, sin(0));
- Output:
5 Attempt to divide by zero. Nil
REBOL
REBOL [
Title: "Detect Divide by Zero"
URL: http://rosettacode.org/wiki/Divide_by_Zero_Detection
]
; The 'try' word returns an error object if the operation fails for
; whatever reason. The 'error?' word detects an error object and
; 'disarm' keeps it from triggering so I can analyze it to print the
; appropriate message. Otherwise, any reference to the error object
; will stop the program.
div-check: func [
"Attempt to divide two numbers, report result or errors as needed."
x y
/local result
] [
either error? result: try [x / y][
result: disarm result
print ["Caught" result/type "error:" result/id]
] [
print [x "/" y "=" result]
]
]
div-check 12 2 ; An ordinary calculation.
div-check 6 0 ; This will detect divide by zero.
div-check "7" 0.0001 ; Other errors can be caught as well.
Output:
12 / 2 = 6 Caught math error: zero-divide Caught script error: cannot-use
REXX
The task's requirements are to write a function, but this example program was written to solve the spirit of the requirement.
This version isn't really a function so much as it is a method.
Also, a function and a subroutine doesn't have that much of a distinction in the REXX language.
/*REXX program demonstrates detection and handling division by zero. */
signal on syntax /*handle all REXX syntax errors. */
x = sourceline() /*being cute, x=is the size of this pgm*/
y = x - x /*setting to zero the obtuse way. */
z = x / y /*this'll trigger it, furrrr shurrre. */
exit /*We're kaput. Ja vohl ! */
/*──────────────────────────────────────────────────────────────────────────────────────*/
err: if rc==42 then do; say /*first, check for a specific error. */
say center(' ***error*** ', 79, "═")
say 'Division by zero detected at line ' @ ,
" and the REXX statement is:"
say sourceLine(@)
say
exit 42
end
say
say center(' error! ', 79, "*")
do #=1 for arg(); say; say arg(#); say
end /*#*/
exit 13
/*──────────────────────────────────────────────────────────────────────────────────────*/
syntax: @=sigl; call err 'REXX program' condition("C") 'error', condition('D'), ,
'REXX source statement (line' sigl"):", sourceLine(sigl)
- output:
═════════════════════════════════ ***error*** ═════════════════════════════════ Division by zero detected at line 5 and the REXX statement is: z = x / y /*this'll trigger it, furrrr shurrre. */
Ring
Try
see 9/0
Catch
see "Catch!" + nl + cCatchError
Done
RPGIV
dcl-c DIVIDE_BY_ZERO 00102;
dcl-s result zoned(5:2);
dcl-s value1 zoned(5:2);
dcl-s value2 zoned(5:2);
value1 = 10;
value2 = 0;
monitor;
eval(h) result = value1 / value2; // Using half rounding here for the eval result
on-error DIVIDE_BY_ZERO;
// Initialise the result to 0. Consider other messaging perhaps.
result = 0;
endmon;
*inlr = *on;
RPL
RPL provides targeted error detection and handling. In case of a division by zero, rather than displaying an error message, the program delivers the attempted arithmetic operation as an expression to be further processed.
≪ IFERR / THEN SWAP "'" SWAP →STR + "/" + SWAP →STR + STR→ END ≫ 'DIV' STO 6 2 DIV 4 0 DIV
- Output:
2: 3 1: '4/0'
Ruby
This only checks integer division by zero.
def div_check(x, y)
begin
x / y
rescue ZeroDivisionError
true
else
false
end
end
Ruby allows division by zero if either operand is a Float.
irb(main):010:0> div_check(5, 0)
=> true
irb(main):011:0> div_check(5.0, 0)
=> false
Starting with Ruby 1.9, Numeric#div raises ZeroDivisionError, whether or not an operand is a Float.
def div_check(x, y)
begin
x.div y
rescue ZeroDivisionError
true
else
false
end
end
irb(main):010:0> div_check(5, 0)
=> true
irb(main):011:0> div_check(5.0, 0)
=> true
Rust
fn test_division(numerator: u32, denominator: u32) {
match numerator.checked_div(denominator) {
Some(result) => println!("{} / {} = {}", numerator, denominator, result),
None => println!("{} / {} results in a division by zero", numerator, denominator)
}
}
fn main() {
test_division(5, 4);
test_division(4, 0);
}
Scala
Without the "println(result)" line, the result would not get calculated as it is not needed. The method would get optimized to always return false.
object DivideByZero extends Application {
def check(x: Int, y: Int): Boolean = {
try {
val result = x / y
println(result)
return false
} catch {
case x: ArithmeticException => {
return true
}
}
}
println("divided by zero = " + check(1, 0))
def check1(x: Int, y: Int): Boolean = {
import scala.util.Try
Try(y/x).isFailure
}
println("divided by zero = " + check1(1, 0))
}
Seed7
Integer division by zero raises NUMERIC_ERROR. Floating point division by zero returns Infinity or -Infinity.
$ include "seed7_05.s7i";
include "float.s7i";
const proc: doDivide (in integer: numer, in integer: denom) is func
begin
block
writeln(numer <& " div " <& denom <& " = " <& numer div denom);
exception
catch NUMERIC_ERROR:
writeln("Division by zero detected.");
end block;
end func;
const proc: doDivide (in float: numer, in float: denom) is func
local
var float: quotient is 0.0;
begin
quotient := numer / denom;
if quotient <> Infinity and quotient <> -Infinity then
writeln(numer <& " / " <& denom <& " = " <& quotient);
else
writeln("Division by zero detected.");
end if;
end func;
const proc: main is func
begin
doDivide(10, 8);
doDivide(1, 0);
doDivide(10.0, 8.0);
doDivide(1.0, 0.0);
end func;
Output:
10 div 8 = 1 Division by zero detected. 10.0 / 8.0 = 1.25 Division by zero detected.
Sidef
The numerical system of Sidef evaluates `x/0` to `+/-Inf`.
func div_check(a, b){
var result = a/b
result.abs == Inf ? nil : result
}
say div_check(10, 2) # 5
say div_check(1, 0) # nil (detected)
Alternatively, we can do:
func div_check(a, b){
Perl.eval("#{a} / #{b}")
}
say div_check(10, 2) # 5
say div_check(1, 0) # nil (detected)
Slate
[ 1 / 0 ] on: Error do: [|:err| err return: PositiveInfinity].
Smalltalk
The behavior is the same for all number types (Integer, Float, Fraction, etc.). ZeroDivision raises an exception which can be caught to abort or proceed with a repair-value.
|didDivideByZero a b|
didDivideByZero := false.
a := 10.
b := 0.
[
a/b
] on: ZeroDivide do:[:ex |
'you tried to divide %P by zero\n' printf:{ex suspendedContext receiver} on:Transcript.
didDivideByZero := true.
].
didDivideByZero ifTrue:[
Transcript show:'bad bad bad, but I already told you in the handler'.
].
Note: works in all Smalltalks: printf is available in the public domain printfScanf package (or already included in your dialect).
Alternative version, which gets any block as argument, evaluates it and returns true, if ZeroDivide happened (works in all Smalltalks):
testZeroDivide :=
[:aBlock |
[
aBlock value.
false
] on: ZeroDivide do: [true].
].
"Testing"
testZeroDivide value: [2/1] "------> false"
testZeroDivide value: [2/0] "------> true"
of course, as ZeroDivide inherits from Error, you could also write
[...] on:Error do: [...]
thereby catching ANY error (as done in some other code examples here).
You can also provide an alternative value from the exception handler:
|a b result|
a := 10. b := 0.
result := [a / b] on:ZeroDivide do:[:ex | ex proceedWith:Float infinity].
Transcript showCR:result.
will show "inf" on the console window.
SNOBOL4
Using setexit( ) to trap and ignore division by zero.
define('zdiv(x,y)') :(zdiv_end)
zdiv &errlimit = 1; setexit(.ztrap)
zdiv = x / y :(return)
ztrap zdiv = ?(&errtype ? (14 | 262)) 'Division by zero' :s(continue)f(abort)
zdiv_end
* # Test and display
output = '1/1 = ' zdiv(1,1) ;* Integers non-zero
output = '1.0/1.0 = ' zdiv(1.0,1.0) ;* Reals non-zero
output = '1/0 = ' zdiv(1,0) ;* Integers zero
output = '1.0/0.0 = ' zdiv(1.0,0.0) ;* Reals zero
output = 'Zero checks complete'
end
Output:
1/1 = 1 1.0/1.0 = 1. 1/0 = Division by zero 1.0/0.0 = Division by zero Zero checks complete
SQL PL
version 9.7 or higher.
With SQL PL:
--#SET TERMINATOR @
SET SERVEROUTPUT ON@
CREATE OR REPLACE FUNCTION DIVISION(
IN NUMERATOR DECIMAL(5, 3),
IN DENOMINATOR DECIMAL(5, 3)
) RETURNS SMALLINT
BEGIN
DECLARE RET SMALLINT DEFAULT 1;
DECLARE TMP DECIMAL(5, 3);
DECLARE CONTINUE HANDLER FOR SQLSTATE '22012'
SET RET = 1;
SET RET = 0;
SET TMP = NUMERATOR / DENOMINATOR;
RETURN RET;
END @
VALUES DIVISION(10, 2)@
VALUES DIVISION(10, 3)@
VALUES DIVISION(10, 0)@
Output:
db2 -td@ db2 => CREATE OR REPLACE FUNCTION DIVISION( ... db2 (cont.) => END @ DB20000I The SQL command completed successfully. VALUES DIVISION(10, 2) 1 ------ 0 1 record(s) selected. VALUES DIVISION(10, 3) 1 ------ 0 1 record(s) selected. VALUES DIVISION(10, 0) 1 ------ 1 1 record(s) selected.
Standard ML
Detection on integers by catching an exception:
fun div_check (x, y) = (
ignore (x div y);
false
) handle Div => true
Detection on floats by checking for infiniteness:
fun div_check (x, y) =
not (Real.isFinite (x / y))
Stata
In stata, a division by zero is silently replaced with a missing value. It would be possible to check whether the result is a missing value, but there may be another cause: one of the arguments is a missing value, or there is an overflow (for instance 1e200/1e-200). Therefore, it's not possible to detect precisely a division by zero, without checking the denominator.
Tcl
proc div_check {x y} {
if {[catch {expr {$x/$y}} result] == 0} {
puts "valid division: $x/$y=$result"
} else {
if {$result eq "divide by zero"} {
puts "caught division by zero: $x/$y -> $result"
} else {
puts "caught another error: $x/$y -> $result"
}
}
}
foreach denom {1 0 foo} {
div_check 42 $denom
}
- Output:
valid division: 42/1=42 caught division by zero: 42/0 -> divide by zero caught another error: 42/foo -> can't use non-numeric string as operand of "/"
It is easier to trap such errors in Tcl 8.6, which has an additional control structure for exception processing:
proc div_check {x y} {
try {
puts "valid division: $x/$y=[expr {$x/$y}]"
} trap {ARITH DIVZERO} msg {
puts "caught division by zero: $x/$y -> $msg"
} trap {ARITH DOMAIN} msg {
puts "caught bad division: $x/$y -> $msg"
} on error msg {
puts "caught another error: $x/$y -> $msg"
}
}
foreach {num denom} {42 1 42 0 42.0 0.0 0 0 0.0 0.0 0 foo} {
div_check $num $denom
}
which produces the
- Output:
valid division: 42/1=42 caught division by zero: 42/0 -> divide by zero valid division: 42.0/0.0=Inf caught division by zero: 0/0 -> divide by zero caught bad division: 0.0/0.0 -> domain error: argument not in valid range caught another error: 0/foo -> can't use non-numeric string as operand of "/"
As can be seen, division-by-zero is only signaled when performing integer division. Similarly, separate detection of values that would otherwise be IEEE NaN is only performed when doing floating-point division.
TXR
@(do (defun div-check (x y)
(catch (/ x y)
(numeric_error (msg)
'div-check-failed))))
@(bind good @(div-check 32 8))
@(bind bad @(div-check 42 0))
Run:
$ txr -B division-by-zero.txr good="4.0" bad="div-check-failed"
Ursa
def div_check (int x, int y)
try
/ x y
return false
catch divzeroerror
return true
end try
end
VAX Assembly
65 64 69 76 69 64 00000008'010E0000' 0000 1 desc: .ascid "divide by zero"
6F 72 65 7A 20 79 62 20 000E
0000 0016 2 .entry handler,0
E5 AF 7F 0018 3 pushaq desc
00000000'GF 01 FB 001B 4 calls #1, g^lib$put_output
04 0022 5 ret
0023 6
0000 0023 7 .entry main,0
6D EE AF 9E 0025 8 movab handler, (fp) ;register exception handler
50 01 00 C7 0029 9 divl3 #0, #1, r0
04 002D 10 ret
002E 11
002E 12 .end main
$ run dv
divide by zero
VBA
Option Explicit
Sub Main()
Dim Div
If CatchDivideByZero(152, 0, Div) Then Debug.Print Div Else Debug.Print "Error"
If CatchDivideByZero(152, 10, Div) Then Debug.Print Div Else Debug.Print "Error"
End Sub
Function CatchDivideByZero(Num, Den, Div) As Boolean
On Error Resume Next
Div = Num / Den
If Err = 0 Then CatchDivideByZero = True
On Error GoTo 0
End Function
- Output:
Error 15,2
VBScript
Function div(num,den)
On Error Resume Next
n = num/den
If Err.Number <> 0 Then
div = Err.Description & " is not allowed."
Else
div = n
End If
End Function
WScript.StdOut.WriteLine div(6,3)
WScript.StdOut.WriteLine div(6,0)
WScript.StdOut.WriteLine div(7,-4)
- Output:
2 Division by zero is not allowed. -1.75
Visual Basic .NET
Module DivByZeroDetection
Sub Main()
Console.WriteLine(safeDivision(10, 0))
End Sub
Private Function safeDivision(v1 As Integer, v2 As Integer) As Boolean
Try
Dim answer = v1 / v2
Return False
Catch ex As Exception
Return True
End Try
End Function
End Module
- Output:
True
V (Vlang)
fn main() {
divide(0, 0)
divide(15, 0)
divide(15, 3)
}
fn divide(x f64, y f64) {
result := x/y
if result.str().contains_any_substr(["inf","nan"]) == true {
println("Can\'t divide by zero!")
return
}
println(result)
}
Alternate version:
fn main() {
divide(0, 0)
divide(15, 0)
divide(15, 3)
}
pub fn divide(x f64, y f64) {
succeed := divide_error_handler(x, y) or {
println(err)
return
}
println(succeed)
}
fn divide_error_handler(x f64, y f64) !f64 {
result := x/y
if result.str().contains_any_substr(["inf","nan"]) == true {
return error("Can\'t divide by zero!")
}
return result
}
- Output:
Can't divide by zero! Can't divide by zero! 5.0
Wren
var checkDivByZero = Fn.new { |a, b|
var c = a / b
if (c.isInfinity || c.isNan) return true
return false
}
System.print("Division by zero?")
System.print(" 0 / 0 -> %(checkDivByZero.call(0, 0))")
System.print(" 1 / 0 -> %(checkDivByZero.call(1, 0))")
System.print(" 1 / 1 -> %(checkDivByZero.call(1, 1))")
- Output:
Division by zero? 0 / 0 -> true 1 / 0 -> true 1 / 1 -> false
XPL0
GetErr is an intrinsic function that detects runtime errors, such as division by zero, as well as more than a dozen others. Normally runtime errors terminate a program and display an error message. However the Trap intrinsic is used here to prevent error termination, which enables the program to do its own error handling. This example displays "Divide by zero".
include c:\cxpl\codes;
int A, B;
[Trap(false); \turn off error trapping
B:= 1234/(A-A); \(error not detected at compile time)
if GetErr then Text(0, "Divide by zero");
]
Yorick
func div_check(x, y) {
if(catch(0x01))
return 1;
temp = x/y;
return 0;
}
zkl
fcn f(x,y){try{x/y}catch(MathError){println(__exception)}}
- Output:
zkl: f(1,0) MathError(INF (number is infinite), Int divide by zero) zkl: f(1.0,0) MathError(INF (number is infinite))
- Programming Tasks
- Solutions by Programming Task
- Simple
- 6502 Assembly/Omit
- 8080 Assembly/Omit
- Z80 Assembly/Omit
- Computer/zero Assembly/Omit
- 68000 Assembly
- 8th
- ABAP
- Ada
- Aime
- ALGOL 68
- ALGOL W
- Arturo
- AutoHotkey
- BASIC
- Applesoft BASIC
- BASIC256
- BBC BASIC
- GW-BASIC
- IS-BASIC
- Liberty BASIC
- Locomotive Basic
- MSX Basic
- PureBasic
- QBasic
- Run BASIC
- SmallBASIC
- TI-89 BASIC
- True BASIC
- Batch File
- BQN
- C
- POSIX
- C sharp
- C++
- Ceylon
- Clojure
- CLU
- COBOL
- Common Lisp
- D
- Delphi
- Déjà Vu
- E
- EasyLang
- ECL
- Eiffel
- Ela
- Elixir
- Emacs Lisp
- Erlang
- ERRE
- F Sharp
- Factor
- Fancy
- Forth
- Fortran
- FreeBASIC
- FutureBasic
- Gambas
- Go
- Groovy
- Haskell
- Hexiscript
- HicEst
- HolyC
- I
- Icon
- Unicon
- IDL
- J
- Java
- JavaScript
- Jq
- Jsish
- Julia
- Kotlin
- Lambdatalk
- LabVIEW
- Langur
- Lasso
- Lingo
- Lua
- M2000 Interpreter
- M4
- Maple
- Mathematica
- Wolfram Language
- MATLAB
- Maxima
- MAXScript
- Min
- MiniScript
- MIRC Scripting Language
- MUMPS
- Nanoquery
- Neko
- NetLogo
- NetRexx
- NewLISP
- Nim
- NS-HUBASIC
- OCaml
- Octave
- Oforth
- Ol
- OoRexx
- Oz
- PARI/GP
- Pascal
- Perl
- Phix
- Phix/basics
- PHP
- PicoLisp
- PL/I
- PL/SQL
- Plain English
- Plain English-output
- PowerShell
- Prolog
- Pure
- Python
- Q
- R
- Racket
- Raku
- REBOL
- REXX
- Ring
- RPGIV
- RPL
- Ruby
- Rust
- Scala
- Seed7
- Sidef
- Slate
- Smalltalk
- SNOBOL4
- SQL PL
- Standard ML
- Stata
- Tcl
- TXR
- Ursa
- VAX Assembly
- VBA
- VBScript
- Visual Basic .NET
- V (Vlang)
- Wren
- XPL0
- Yorick
- Zkl
- ACL2/Omit
- AWK/Omit
- Bc/Omit
- CMake/Omit
- Dc/Omit
- MIPS Assembly/Omit
- Retro/Omit
- Sed/Omit
- Swift/Omit
- Pages with too many expensive parser function calls