Detect division by zero: Difference between revisions

(Add CLU)
 
(25 intermediate revisions by 11 users not shown)
Line 2:
[[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:
Write a function to detect a   ''divide by zero error''   without checking if the denominator is zero.
Line 11 ⟶ 13:
=={{header|8th}}==
Division by zero results in the value "Inf":
<syntaxhighlight lang="forth">
<lang Forth>
1 0 n:/ Inf? . cr
</syntaxhighlight>
</lang>
{{out}}<pre>true</pre>
 
=={{header|ABAP}}==
<langsyntaxhighlight ABAPlang="abap">report zdiv_zero
data x type i.
try.
Line 24 ⟶ 26:
write 'Divide by zero.'.
endtry.
</syntaxhighlight>
</lang>
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">-- Divide By Zero Detection
 
with Ada.Text_Io; use Ada.Text_Io;
Line 58 ⟶ 60:
end if;
New_Line;
end Divide_By_Zero;</langsyntaxhighlight>
{{out}}
<pre>
Line 66 ⟶ 68:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">integer
divide(integer n, integer d)
{
Line 86 ⟶ 88:
 
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 114 ⟶ 116:
 
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}}
<langsyntaxhighlight lang="algol68">PROC raise exception= ([]STRING args)VOID: (
put(stand error, ("Exception: ",args, newline));
stop
Line 139 ⟶ 141:
raise zero division error := a different handler;
print(x/y)
END</langsyntaxhighlight>
{{out}}
<pre>
Line 149 ⟶ 151:
<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.
<langsyntaxhighlight lang="algolw">begin
% integer division procedure %
% sets c to a divided by b, returns true if the division was OK, %
Line 176 ⟶ 178:
write( divideR( 4, 2, d ) ); % prints false as no exception %
write( divideR( 5, 0, d ) ) % prints true as division by zero was detected %
end.</langsyntaxhighlight>
 
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">try? -> 3/0
else -> print "division by zero" </langsyntaxhighlight>
 
{{out}}
Line 188 ⟶ 190:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">ZeroDiv(num1, num2) {
If ((num1/num2) != "")
MsgBox % num1/num2
Line 195 ⟶ 197:
}
ZeroDiv(0, 3) ; is ok
ZeroDiv(3, 0) ; divize by zero alert</langsyntaxhighlight>
 
=={{header|BASIC}}==
Line 201 ⟶ 203:
==={{header|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
 
<langsyntaxhighlight BASIClang="basic"> 100 REM TRY
110 ONERR GOTO 200
120 D = - 44 / 0
Line 213 ⟶ 215:
240 CALL - 3288: REM RECOVER
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}}===
<langsyntaxhighlight lang="bbcbasic"> PROCdivide(-44, 0)
PROCdivide(-44, 5)
PROCdivide(0, 5)
Line 234 ⟶ 248:
ENDCASE
ENDIF
ENDPROC</langsyntaxhighlight>
 
==={{header|GW-BASIC}}===
The [[#Locomotive_BASIC|Locomotive BASIC]] solution works without any changes.
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="is-BASICbasic">100 WHEN EXCEPTION USE ERROR
110 FOR I=5 TO-2 STEP-1
120 PRINT 10/I
Line 245 ⟶ 262:
160 IF EXTYPE=3001 THEN PRINT EXSTRING$(EXTYPE);" in line";EXLINE
170 CONTINUE
180 END HANDLER</langsyntaxhighlight>
 
==={{header|Liberty BASIC}}===
<langsyntaxhighlight lang="lb">result = DetectDividebyZero(1, 0)
 
 
Function DetectDividebyZero(a, b)
Line 259 ⟶ 275:
Notice "Divide by Zero Detected!"
End If
End Function</langsyntaxhighlight>
 
==={{header|Locomotive Basic}}===
<langsyntaxhighlight lang="locobasic">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</langsyntaxhighlight>
 
{{out}}
Line 274 ⟶ 290:
Division by zero in line 40 </pre>
 
==={{header|PureBasicMSX 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;
*ErrorAddress()
Line 298 ⟶ 316:
 
'''With Integers & OnError Library'''
<langsyntaxhighlight PureBasiclang="purebasic">;Set up a Procedure to handle any Error
Procedure MyErrorHandler()
Define txt$="The following error happened."+#CRLF$+ ErrorMessage()+"at line "+Str(ErrorLine())
Line 310 ⟶ 328:
Repeat
A=Random(100)/Random(100)
ForEver</langsyntaxhighlight>
[[Image:OnError.png]]
 
 
'''With Floats, and without OnError library'''
<langsyntaxhighlight PureBasiclang="purebasic">Define.d a, b
Debug a/b</langsyntaxhighlight>
Results in;
<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}}===
<langsyntaxhighlight lang="runbasic">on error goto [error]
a = 1 / 0
wait
Line 327 ⟶ 356:
[error] ' error 11 is division by zero err number
If err = 11 Then print "Division by Zero"
wait</langsyntaxhighlight>
 
==={{header|TI-89 BASIC}}===
<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}}==
<langsyntaxhighlight lang="dos">@echo off
set /a dummy=5/0 2>nul
 
if %errorlevel%==1073750993 echo I caught a division by zero operation...
exit /b 0</langsyntaxhighlight>
 
=={{header|BQN}}==
Line 344 ⟶ 384:
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.
 
<langsyntaxhighlight lang="bqn">Div ← {∨´"∞"‿"NaN"≡¨<•Fmt𝕩}◶⊢‿"Division by 0"÷
 
•Show 5 Div 0
•Show 5 Div 5
•Show 0 Div 0</langsyntaxhighlight><syntaxhighlight lang ="bqn">"Division by 0"
1
"Division by 0"</langsyntaxhighlight>
 
[https://mlochbaum.github.io/BQN/try.html#code=RGl2IOKGkCB74oiowrQi4oieIuKAvyJOYU4i4omhwqg84oCiRm108J2VqX3il7biiqLigL8iRGl2aXNpb24gYnkgMCLDtwoK4oCiU2hvdyA1IERpdiAwCuKAolNob3cgNSBEaXYgNQrigKJTaG93IDAgRGl2IDA= Try It!]
Line 364 ⟶ 404:
Some systems will raise SIGFPE if a program divides by zero.
 
<langsyntaxhighlight lang="c">#include <limits.h> /* INT_MIN */
#include <setjmp.h> /* siglongjmp(), sigsetjmp() */
#include <stdio.h> /* perror(), printf() */
Line 463 ⟶ 503:
try_division(INT_MIN, -1);
return 0;
}</langsyntaxhighlight>
 
{{out}} using OpenBSD/amd64:
Line 478 ⟶ 518:
The floating point types (float, double) don't raise an exception, but return the values Infinity or NaN as appropriate.
 
<langsyntaxhighlight lang="csharp">using System;
 
namespace RosettaCode {
Line 493 ⟶ 533:
}
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">
#include<iostream>
#include<csignal> /* for signal */
Line 520 ⟶ 560:
return 0;
}
</syntaxhighlight>
</lang>
 
=={{header|Ceylon}}==
<langsyntaxhighlight lang="ceylon">shared void run() {
//integers divided by zero throw an exception
Line 534 ⟶ 574:
//floats divided by zero produce infinity
print(1.0 / 0 == infinity then "division by zero!" else "not division by zero!");
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
Line 541 ⟶ 581:
return +inf, if 0, NaN, otherwise -inf.
 
<langsyntaxhighlight lang="lisp">(defn safe-/ [x y]
(try (/ x y)
(catch ArithmeticException _
Line 547 ⟶ 587:
(cond (> x 0) Double/POSITIVE_INFINITY
(zero? x) Double/NaN
:else Double/NEGATIVE_INFINITY) )))</langsyntaxhighlight>
 
=={{header|CLU}}==
<langsyntaxhighlight 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.
Line 582 ⟶ 622:
end
end
end start_up</langsyntaxhighlight>
{{out}}
<pre>10/2 = 5
Line 589 ⟶ 629:
 
=={{header|COBOL}}==
<langsyntaxhighlight lang="cobol">DIVIDE foo BY bar GIVING foobar
ON SIZE ERROR
DISPLAY "Division by zero detected!"
END-DIVIDE</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
 
<langsyntaxhighlight lang="lisp">(handler-case (/ x y)
(division-by-zero () (format t "division by zero caught!~%")))</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.string, std.math, std.traits;
 
string divCheck(T)(in T numer, in T denom)
Line 652 ⟶ 692:
divCheck(real.infinity, real.infinity));
writefln("real nan/ nan: %s", divCheck(real.nan, real.nan));
}</langsyntaxhighlight>
{{out}}
<pre>Division with check:
Line 673 ⟶ 713:
 
=={{header|Delphi}}==
<langsyntaxhighlight Delphilang="delphi">program DivideByZero;
 
{$APPTYPE CONSOLE}
Line 690 ⟶ 730:
Writeln(e.Message);
end;
end.</langsyntaxhighlight>
 
=={{header|Déjà Vu}}==
<langsyntaxhighlight lang="dejavu">divcheck x y:
true
try:
Line 703 ⟶ 743:
!print "Okay"
else:
!print "Division by zero"</langsyntaxhighlight>
{{out}}
<pre>Division by zero</pre>
Line 709 ⟶ 749:
=={{header|E}}==
 
<langsyntaxhighlight lang="e">def divide(numerator, denominator) {
def floatQuotient := numerator / denominator
if (floatQuotient.isNaN() || floatQuotient.isInfinite()) {
Line 716 ⟶ 756:
return ["ok", floatQuotient]
}
}</langsyntaxhighlight>
 
=={{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}}==
Line 722 ⟶ 774:
 
Evaluate to zero - default behavior
<syntaxhighlight lang="ecl">
<lang ECL>
DBZ(REAL8 Dividend,INTEGER8 Divisor) := Quotient/Divisor;
 
#option ('divideByZero', 'zero');
DBZ(10,0); //returns 0.0
</syntaxhighlight>
</lang>
Stop and report a division by zero error:
<syntaxhighlight lang="ecl">
<lang ECL>
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,"
</syntaxhighlight>
</lang>
Returns "nan":
<syntaxhighlight lang="ecl">
<lang ECL>
DBZ(REAL8 Dividend,INTEGER8 Divisor) := Quotient/Divisor;
#option ('divideByZero', 'nan');
Line 745 ⟶ 797:
Integer and decimal division by zero continue to return 0.
*/
</syntaxhighlight>
</lang>
 
=={{header|Eiffel}}==
Line 751 ⟶ 803:
 
In a file called main.e:
<langsyntaxhighlight lang="eiffel">class MAIN
creation main
feature main is
Line 771 ⟶ 823:
retry
end
end</langsyntaxhighlight>
Note: The "rescue" statement catches ''every'' exception.
 
=={{header|Ela}}==
 
<langsyntaxhighlight lang="ela">open core number
 
x /. y = try Some (x `div` y) with
_ = None
(12 /. 2, 12 /. 0)</langsyntaxhighlight>
 
Output:
Line 789 ⟶ 841:
Of course the cleanest way to implement the safe division function is through pattern matching:
 
<langsyntaxhighlight lang="ela">x /. 0 = None
x /. y = Some (x / y)</langsyntaxhighlight>
 
But it doesn't satisfy the task.
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Division do
def by_zero?(x,y) do
try do
Line 809 ⟶ 861:
|> Enum.each(fn {x,y} ->
IO.puts "#{x} / #{y}\tdivision by zero #{Division.by_zero?(x,y)}"
end)</langsyntaxhighlight>
 
{{out}}
Line 826 ⟶ 878:
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"].
 
<langsyntaxhighlight Lisplang="lisp">(condition-case nil
(/ 1 0)
(arith-error
(message "Divide by zero (either integer or float)")))</langsyntaxhighlight>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">div_check(X,Y) ->
case catch X/Y of
{'EXIT',_} -> true;
_ -> false
end.</langsyntaxhighlight>
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM DIV_BY_ZERO
 
Line 850 ⟶ 902:
PRINT(3/0)
END PROGRAM
</syntaxhighlight>
</lang>
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.
Line 860 ⟶ 912:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">let detectDivideZero (x : int) (y : int):int option =
try
Some(x / y)
Line 868 ⟶ 920:
 
printfn "12 divided by 3 is %A" (detectDivideZero 12 3)
printfn "1 divided by 0 is %A" (detectDivideZero 1 0)</langsyntaxhighlight>
 
Output:
Line 875 ⟶ 927:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USE: math.floats.env
 
: try-div ( a b -- )
'[ { +fp-zero-divide+ } [ _ _ /f . ] with-fp-traps ] try ;</langsyntaxhighlight>
 
( scratchpad ) 1 2 try-div
Line 888 ⟶ 940:
 
=={{header|Fancy}}==
<langsyntaxhighlight lang="fancy">def divide: x by: y {
try {
x / y
Line 895 ⟶ 947:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: safe-/ ( x y -- x/y )
['] / catch -55 = if cr ." divide by zero!" 2drop 0 then ;</langsyntaxhighlight>
 
=={{header|Fortran}}==
Line 906 ⟶ 958:
Floating-point division by zero detection.
 
<langsyntaxhighlight lang="fortran">
program rosetta_divbyzero
implicit none
Line 948 ⟶ 1,000:
 
end program rosetta_divbyzero
</syntaxhighlight>
</lang>
 
Integer division by zero. No detection.
 
<langsyntaxhighlight lang="fortran">
program rosetta_integer_divbyzero
implicit none
Line 961 ⟶ 1,013:
write(*,*) answer
end program rosetta_integer_divbyzero
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
Line 972 ⟶ 1,024:
The following code relies on this 'hack':-
 
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Const divByZeroResult As Integer = -9223372036854775808
Line 996 ⟶ 1,048:
Print
Print "Press any key to exit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,008 ⟶ 1,060:
=={{header|FutureBasic}}==
Stop on error. Error type reported in log console.
<langsyntaxhighlight lang="futurebasic">
include "ConsoleWindow"
 
on error stop
dim as long a
print a / 0
 
</lang>
HandleEvents
</syntaxhighlight>
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=6c837b97d9c5f296ef23245706544bdf Click this link to run this code]'''
<langsyntaxhighlight lang="gambas">Public Sub Main()
 
Try Print 1 / 0
If Error Then Print Error.Text
 
End</langsyntaxhighlight>
Output:
<pre>
Line 1,031 ⟶ 1,083:
=={{header|Go}}==
Detection on integers by recovering from a panic:
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,046 ⟶ 1,098:
fmt.Println(divCheck(3, 2))
fmt.Println(divCheck(3, 0))
}</langsyntaxhighlight>
Output:
<pre>
Line 1,055 ⟶ 1,107:
=={{header|Groovy}}==
In Groovy, the float and double types follow IEEE numeric formats and rules. Here is a solution for double:
<langsyntaxhighlight lang="groovy">def dividesByZero = { double n, double d ->
assert ! n.infinite : 'Algorithm fails if the numerator is already infinite.'
(n/d).infinite || (n/d).naN
}</langsyntaxhighlight>
 
Test program:
<langsyntaxhighlight lang="groovy">((3d)..(0d)).each { i ->
((2d)..(0d)).each { j ->
println "${i}/${j} divides by zero? " + dividesByZero(i,j)
}
}</langsyntaxhighlight>
 
Output:
Line 1,082 ⟶ 1,134:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import qualified Control.Exception as C
check x y = C.catch (x `div` y `seq` return False)
(\_ -> return True)</langsyntaxhighlight>
 
=={{header|hexiscript}}==
<langsyntaxhighlight lang="hexiscript">let a 1
let b 0
if tostr (a / (b + 0.)) = "inf"
Line 1,093 ⟶ 1,145:
else
println a / b
endif</langsyntaxhighlight>
 
=={{header|HicEst}}==
<langsyntaxhighlight lang="hicest">FUNCTION zero_divide(num, denom)
XEQ( num// "/" // denom, *99) ! on error jump to label 99
zero_divide = 0 ! division OK
Line 1,102 ⟶ 1,154:
 
99 zero_divide = 1
END</langsyntaxhighlight>
<langsyntaxhighlight lang="hicest">zero_divide(0, 1) returns 0 (false)
zero_divide( 1, 3-2-1 ) returns 1 (true)</langsyntaxhighlight>
 
=={{header|HolyC}}==
HolyC throws <code>Except:DivZero</code>.
<langsyntaxhighlight lang="holyc">try {
Print("%d\n", 10 / 0);
} catch {
Print("Divide by zero");
}</langsyntaxhighlight>
 
=={{header|i}}==
<langsyntaxhighlight lang="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
Line 1,129 ⟶ 1,181:
IsDivisionByZero(5, 2)
IsDivisionByZero(0, 0)
}</langsyntaxhighlight>
 
=={{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
<langsyntaxhighlight Iconlang="icon">procedure main()
&error := 1
udef := 1 / 0 | stop("Run-time error ", &errornumber, " : ", &errortext," in line #",&line," - converted to failure")
end</langsyntaxhighlight>
 
Sample Output:<pre>Run-time error 201 : division by zero in line #3 - converted to failure</pre>
Line 1,142 ⟶ 1,194:
=={{header|IDL}}==
 
<langsyntaxhighlight lang="idl">if not finite( <i>expression</i> ) then ...</langsyntaxhighlight>
 
=={{header|J}}==
Line 1,153 ⟶ 1,205:
So, anyways, the task:
 
<langsyntaxhighlight Jlang="j">funnydiv=: 0 { [: (,:'division by zero detected')"_^:(_ e. |@,) (,>:)@:(,:^:(0<#@$))@[ %"_1 _ ]</langsyntaxhighlight>
 
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,159 ⟶ 1,211:
Examples:
 
<langsyntaxhighlight Jlang="j"> 3 funnydiv 2
1.5
3 funnydiv 0
Line 1,168 ⟶ 1,220:
0
2 3 4 funnydiv 5
0.4 0.6 0.8</langsyntaxhighlight>
 
=={{header|Java}}==
Line 1,174 ⟶ 1,226:
 
One way to do this check in Java is to use the <tt>isInfinite</tt> function from the <tt>Double</tt> class:
<langsyntaxhighlight lang="java">public static boolean infinity(double numer, double denom){
return Double.isInfinite(numer/denom);
}</langsyntaxhighlight>
Another way is to use the <tt>ArithmeticException</tt> as a check (which is not preferred because it expects an exception):
<langsyntaxhighlight lang="java">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;}
}</langsyntaxhighlight>
 
=={{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):
<langsyntaxhighlight JavaScriptlang="javascript">function divByZero(dividend,divisor)
{
var quotient=dividend/divisor;
Line 1,193 ⟶ 1,245:
return quotient; //Will return Infinity or -Infinity in cases of, for example, 5/0 or -7/0 respectively
}
alert(divByZero(0,0));</langsyntaxhighlight>
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,200 ⟶ 1,252:
 
We can however define div(x;y) so that it raises an error, "NaN", if y equals 0:
<langsyntaxhighlight lang="jq">def div(x;y): if y==0 then error("NaN") else x/y end;</langsyntaxhighlight>
In versions of jq since 1.4, we can then catch the error, as illustrated by the following snippet:<langsyntaxhighlight lang="jq">
try div(3;0) catch if "NaN" then "div by 0 error detected" else . end</langsyntaxhighlight>
 
=={{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:
 
<langsyntaxhighlight lang="javascript">if (!isFinite(numerator/denominator)) puts("result is infinity or not a number");</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="julia">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</langsyntaxhighlight>
 
{{out}}
Line 1,226 ⟶ 1,278:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1
 
fun divideByZero(x: Int, y:Int): Boolean =
Line 1,245 ⟶ 1,297:
println("$x / $y = ${x / y}")
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,255 ⟶ 1,307:
 
Thanks to Javascript a division by zero doesn't throw an error, just the word "Infinity".
<langsyntaxhighlight lang="scheme">
{def DivByZero?
{lambda {:w}
Line 1,264 ⟶ 1,316:
{DivByZero? {/ 3 0}}
-> true
</syntaxhighlight>
</lang>
 
=={{header|LabVIEW}}==
Line 1,270 ⟶ 1,322:
 
If the division node receives zero on both nodes (0/0), the Result will be "NaN"
 
=={{header|langur}}==
<syntaxhighlight lang="langur">val .div = 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 .div(3, 2)
writeln .div(3, 0)
</syntaxhighlight>
 
{{out}}
<pre>[1.5, true]
[0, false]
</pre>
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">define dividehandler(a,b) => {
(
#a->isNotA(::integer) && #a->isNotA(::decimal) ||
Line 1,284 ⟶ 1,358:
}
 
dividehandler(1,0)</langsyntaxhighlight>
 
{{out}}
Line 1,290 ⟶ 1,364:
 
=={{header|Lingo}}==
<langsyntaxhighlight lang="lingo">on div (a, b)
-- for simplicity type check of vars omitted
res = value("float(a)/b")
Line 1,298 ⟶ 1,372:
return res
end if
end</langsyntaxhighlight>
 
=={{header|Lua}}==
Lua, like Javascript, does not error on DIVIDE-BY-ZERO, but returns infinity, -infinity or -nan. So:
 
<langsyntaxhighlight lang="lua">local function div(a,b)
if b == 0 then error() end
return a/b
end</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
Line 1,312 ⟶ 1,386:
 
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">
<lang M2000 Interpreter>
Print function("{Read x : =x**2}", 2)=4
</syntaxhighlight>
</lang>
 
For a fast way to check a valid expression we can use Valid()
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Print Valid(100/0)=False
</syntaxhighlight>
</lang>
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
Function DetectDivisionByZero(&a()) {
Line 1,338 ⟶ 1,412:
}
Checkit
</syntaxhighlight>
</lang>
 
=={{header|M4}}==
<langsyntaxhighlight M4lang="m4">ifelse(eval(2/0),`',`detected divide by zero or some other error of some kind')</langsyntaxhighlight>
 
Output, with standard output labeled "==>" and error output labeled "error==>":
Line 1,351 ⟶ 1,425:
=={{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.
<langsyntaxhighlight Maplelang="maple">1/0; # Here is the default behavior.</langsyntaxhighlight>
Output:
<pre>Error, numeric exception: division by zero</pre>
Here is a simple custom handler being installed and used.
<langsyntaxhighlight Maplelang="maple">NumericEventHandler( ':-division_by_zero'
= proc() infinity; end proc ):
 
1/0;
 
NumericStatus(':-division_by_zero'); # We may check the status flag</langsyntaxhighlight>
Output:
<pre> infinity
Line 1,366 ⟶ 1,440:
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.
<langsyntaxhighlight Maplelang="maple">NumericEventHandler( ':-division_by_zero'
= proc()
WARNING("division by zero");
Line 1,375 ⟶ 1,449:
1/0;
 
NumericStatus(':-division_by_zero');</langsyntaxhighlight>
Output:
<pre>Warning, division by zero
Line 1,383 ⟶ 1,457:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">Check[2/0, Print["division by 0"], Power::infy]</langsyntaxhighlight>
 
=={{header|MATLAB}}==
<langsyntaxhighlight Matlablang="matlab">function [isDividedByZero] = dividebyzero(numerator, denomenator)
isDividedByZero = isinf( numerator/denomenator );
% If isDividedByZero equals 1, divide by zero occured.</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">f(a, b) := block([q: errcatch(a / b)], if emptyp(q) then 'error else q[1]);
 
f(5, 6);
Line 1,397 ⟶ 1,471:
 
f(5, 0;)
'error</langsyntaxhighlight>
 
=={{header|MAXScript}}==
<langsyntaxhighlight lang="maxscript">if not bit.isFinite (<i>expression</i>) then...</langsyntaxhighlight>
 
=={{header|min}}==
{{works with|min|0.19.3}}
The following operator will detect division by zero since the result will be infinity.
<langsyntaxhighlight lang="min">(/ inf ==) :div-zero?</langsyntaxhighlight>
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}}==
<langsyntaxhighlight lang="mirc">var %n = $rand(0,1)
if ($calc(1/ %n) == $calc((1/ %n)+1)) {
echo -ag Divides By Zero
Line 1,415 ⟶ 1,525:
else {
echo -ag Does Not Divide By Zero
}</langsyntaxhighlight>
 
=={{header|MUMPS}}==
<langsyntaxhighlight MUMPSlang="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.
Line 1,428 ⟶ 1,538:
DIVFIX
IF $FIND($ECODE,",M9,")>1 WRITE !,"Error: Division by zero" SET $ECODE="" QUIT ""
QUIT "" ; Fall through for other errors</langsyntaxhighlight>
Output:<pre>
USER>W $$DIV^ROSETTA(1,2)
Line 1,445 ⟶ 1,555:
 
=={{header|Nanoquery}}==
<langsyntaxhighlight Nanoquerylang="nanoquery">def div_check(x, y)
try
(x / y)
Line 1,452 ⟶ 1,562:
return true
end
end</langsyntaxhighlight>
 
=={{header|Neko}}==
Float, non-float as infinity and catching an $idiv. *Not demonstrated in a function.*
 
<syntaxhighlight lang="actionscript">/**
<lang ActionScript>/**
Detect division by zero
*/
Line 1,467 ⟶ 1,577:
if $isinfinite(ans) $print("division by zero: ", ans, "\n")
 
try $print($idiv(1, 0)) catch problem $print("idiv by zero: ", problem, "\n")</langsyntaxhighlight>
 
{{out}}
Line 1,478 ⟶ 1,588:
 
=={{header|NetLogo}}==
<langsyntaxhighlight lang="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.
Line 1,500 ⟶ 1,610:
]
[ output-print (word a " / " b " is not calculable"
]</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 1,526 ⟶ 1,636:
say dividend '/' divisor '=' divide(dividend, divisor)
return
</syntaxhighlight>
</lang>
Output:
<pre>netrexx.lang.DivideException: Divide by 0
Line 1,535 ⟶ 1,645:
 
=={{header|NewLISP}}==
<langsyntaxhighlight lang="newlisp">#! /usr/local/bin/newlisp
 
(define (check-division x y)
Line 1,549 ⟶ 1,659:
(println (check-division 11 0))
 
(exit)</langsyntaxhighlight>
 
Output:
Line 1,569 ⟶ 1,679:
It is possible to declare the checks to activate or deactivate in some parts of code using a pragma, as in the following example.
 
<langsyntaxhighlight lang="nim">{.push overflowChecks: on.}
proc divCheck(x, y): bool =
try:
Line 1,578 ⟶ 1,688:
{.pop.} # Restore default check settings
 
echo divCheck(2, 0)</langsyntaxhighlight>
 
=={{header|NS-HUBASIC}}==
<langsyntaxhighlight NSlang="ns-HUBASIChubasic">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</langsyntaxhighlight>
 
=={{header|OCaml}}==
Detection on integers by catching an exception:
<langsyntaxhighlight lang="ocaml">let div_check x y =
try
ignore (x / y);
false
with Division_by_zero ->
true</langsyntaxhighlight>
 
Detection on floats by checking for infiniteness:
<langsyntaxhighlight lang="ocaml">let div_check x y =
classify_float (x /. y) = FP_infinite</langsyntaxhighlight>
 
=={{header|Octave}}==
Line 1,604 ⟶ 1,714:
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.
 
<langsyntaxhighlight lang="octave">d = 5/0;
if ( isinf(d) )
if ( index(lastwarn(), "division by zero") > 0 )
error("division by zero")
endif
endif</langsyntaxhighlight>
 
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">: divideCheck(n)
| e |
try: e [ 128 n / ] when: [ "Zero detected..." . ]
"Leaving" println ;</langsyntaxhighlight>
 
=={{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!
 
<langsyntaxhighlight lang="scheme">
(define (safediv a b)
(if (eq? (type b) type-complex)
Line 1,639 ⟶ 1,749:
(safediv 5 7/5) ; => 25/7
))
</syntaxhighlight>
</lang>
 
=={{header|ooRexx}}==
<langsyntaxhighlight ooRexxlang="oorexx">/* REXX **************************************************************
* program demonstrates detects and handles division by zero.
* translated from REXX:
Line 1,659 ⟶ 1,769:
Say sourceline(sigl)
Say 'rc='rc '('errortext(rc)')'
Exit 12</langsyntaxhighlight>
Output:
<pre>Syntax raised in line 11
Line 1,667 ⟶ 1,777:
=={{header|Oz}}==
For integer division only.
<langsyntaxhighlight lang="oz">try
{Show 42 div 0}
catch error(kernel(div0 ...) ...) then
{System.showInfo "Division by zero detected."}
end</langsyntaxhighlight>
 
=={{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.
 
<langsyntaxhighlight lang="parigp">iferr(1/0,
err,
print("division by 0"); print("or other non-invertible divisor"),
errname(err) == "e_INV");</langsyntaxhighlight>
 
Or the previous <code>trap()</code>,
 
<langsyntaxhighlight lang="parigp">trap(,"division by 0",m/n)</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 1,690 ⟶ 1,800:
=={{header|Perl}}==
This function returns true iff its second argument is zero.
<langsyntaxhighlight lang="perl">sub div_check
{local $@;
eval {$_[0] / $_[1]};
$@ and $@ =~ /division by zero/;}</langsyntaxhighlight>
 
=={{header|Phix}}==
{{libheader|Phix/basics}}
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #008080;">try</span>
<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>
Line 1,704 ⟶ 1,814:
<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;">)
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 1,713 ⟶ 1,823:
=={{header|PHP}}==
This function returns true iff its second argument is zero.
<langsyntaxhighlight lang="php">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'] != '';
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="php">function div_check($x, $y) {
return @($x / $y) === FALSE; // works at least in PHP/5.2.6-3ubuntu4.5
}</langsyntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(catch '("Div/0") (/ A B))</langsyntaxhighlight>
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">Proc DivideDZ(a,b) Returns(Float Bin(33));
Dcl (a,b,c) Float Bin(33);
On ZeroDivide GoTo MyError;
Line 1,737 ⟶ 1,847:
End DivideDZ;
 
xx=DivideDZ(1,0);</langsyntaxhighlight>
 
=={{header|PL/SQL}}==
<langsyntaxhighlight PLSQLlang="plsql">FUNCTION divide(n1 IN NUMBER, n2 IN NUMBER)
RETURN BOOLEAN
IS
Line 1,750 ⟶ 1,860:
WHEN ZERO_DIVIDE THEN
RETURN(true);
end divide;</langsyntaxhighlight>
 
<langsyntaxhighlight PLlang="pl/SQLsql">divide(0,1) --false
divide(1,0) --true, division by zero</langsyntaxhighlight>
 
=={{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}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function div ($a, $b) {
try{$a/$b}
Line 1,763 ⟶ 1,889:
div 10 2
div 1 0
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,771 ⟶ 1,897:
 
=={{header|Prolog}}==
<langsyntaxhighlight lang="prolog">
div(A, B, C, Ex) :-
catch((C is A/B), Ex, (C = infinity)).
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,788 ⟶ 1,914:
Floating point division yields inf or nan values as appropriate (if the FPU supports IEEE 754):
 
<langsyntaxhighlight lang="pure">> 1/0, -1/0, 0/0;
inf,-inf,nan</langsyntaxhighlight>
 
It's possible to check for these values as follows:
 
<langsyntaxhighlight lang="pure">> inf_or_nan x = infp x || nanp x;
> map inf_or_nan [1/0, -1/0, 0/0];
[1,1,1]</langsyntaxhighlight>
 
In contrast, integer division by zero raises an exception which can be caught as follows:
 
<langsyntaxhighlight lang="pure">> divide n m = catch (\_ -> "divide by 0") (n div m);
> divide 0 1;
0
> divide 1 0;
"divide by 0"</langsyntaxhighlight>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">def div_check(x, y):
try:
x / y
Line 1,812 ⟶ 1,938:
return True
else:
return False</langsyntaxhighlight>
 
=={{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>).
 
<langsyntaxhighlight lang="q">r:x%0
?[1=sum r=(0n;0w;-0w);"division by zero detected";()]</langsyntaxhighlight>
 
=={{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:
<langsyntaxhighlight lang="rsplus">d <- 5/0
if ( !is.finite(d) ) {
# it is Inf, -Inf, or NaN
}</langsyntaxhighlight>
 
=={{header|Racket}}==
Line 1,831 ⟶ 1,957:
In Racket, the division by zero exception can be caught directly:
 
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 1,837 ⟶ 1,963:
(λ (e) (displayln "Divided by zero"))])
(/ 1 0))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
====Try/Catch====
<syntaxhighlight lang="raku" perl6line>sub div($a, $b) {
my $r;
try {
Line 1,853 ⟶ 1,979:
}
say div(10,2);
say div(1, sin(0));</langsyntaxhighlight>
{{out}}
<pre>5
Line 1,860 ⟶ 1,986:
 
====Multi Method Dispatch====
<syntaxhighlight lang="raku" perl6line>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));</langsyntaxhighlight>
{{out}}
<pre>5
Line 1,871 ⟶ 1,997:
 
=={{header|REBOL}}==
<langsyntaxhighlight REBOLlang="rebol">REBOL [
Title: "Detect Divide by Zero"
URL: http://rosettacode.org/wiki/Divide_by_Zero_Detection
Line 1,897 ⟶ 2,023:
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.</langsyntaxhighlight>
 
Output:
Line 1,909 ⟶ 2,035:
<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.
<langsyntaxhighlight lang="rexx">/*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*/
Line 1,931 ⟶ 2,057:
/*──────────────────────────────────────────────────────────────────────────────────────*/
syntax: @=sigl; call err 'REXX program' condition("C") 'error', condition('D'), ,
'REXX source statement (line' sigl"):", sourceLine(sigl)</langsyntaxhighlight>
{{out|output|text=}}
<pre>
Line 1,940 ⟶ 2,066:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
Try
see 9/0
Line 1,946 ⟶ 2,072:
see "Catch!" + nl + cCatchError
Done
</syntaxhighlight>
</lang>
 
=={{header|RPGIV}}==
<langsyntaxhighlight lang="rpgiv">
dcl-c DIVIDE_BY_ZERO 00102;
 
Line 1,967 ⟶ 2,093:
 
*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}}==
This only checks integer division by zero.
 
<langsyntaxhighlight lang="ruby">def div_check(x, y)
begin
x / y
Line 1,980 ⟶ 2,121:
false
end
end</langsyntaxhighlight>
 
Ruby allows division by zero if either operand is a Float.
 
<langsyntaxhighlight lang="ruby">irb(main):010:0> div_check(5, 0)
=> true
irb(main):011:0> div_check(5.0, 0)
=> false</langsyntaxhighlight>
 
----
Line 1,995 ⟶ 2,136:
{{works with|Ruby|1.9}}
 
<langsyntaxhighlight lang="ruby">def div_check(x, y)
begin
x.div y
Line 2,003 ⟶ 2,144:
false
end
end</langsyntaxhighlight>
 
<langsyntaxhighlight lang="ruby">irb(main):010:0> div_check(5, 0)
=> true
irb(main):011:0> div_check(5.0, 0)
=> true</langsyntaxhighlight>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">fn test_division(numerator: u32, denominator: u32) {
match numerator.checked_div(denominator) {
Some(result) => println!("{} / {} = {}", numerator, denominator, result),
Line 2,021 ⟶ 2,162:
test_division(5, 4);
test_division(4, 0);
}</langsyntaxhighlight>
 
=={{header|Scala}}==
Line 2,027 ⟶ 2,168:
as it is not needed. The method would get optimized to
always return false.
<langsyntaxhighlight lang="scala">object DivideByZero extends Application {
def check(x: Int, y: Int): Boolean = {
Line 2,049 ⟶ 2,190:
println("divided by zero = " + check1(1, 0))
 
}</langsyntaxhighlight>
 
=={{header|Seed7}}==
Integer division by zero raises NUMERIC_ERROR.
Floating point division by zero returns [http://seed7.sourceforge.net/libraries/float.htm#Infinity Infinity] or -Infinity.
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "float.s7i";
 
Line 2,085 ⟶ 2,226:
doDivide(10.0, 8.0);
doDivide(1.0, 0.0);
end func;</langsyntaxhighlight>
 
Output:
Line 2,097 ⟶ 2,238:
=={{header|Sidef}}==
The numerical system of Sidef evaluates `x/0` to `+/-Inf`.
<langsyntaxhighlight lang="ruby">func div_check(a, b){
var result = a/b
result.abs == Inf ? nil : result
Line 2,103 ⟶ 2,244:
 
say div_check(10, 2) # 5
say div_check(1, 0) # nil (detected)</langsyntaxhighlight>
 
Alternatively, we can do:
 
<langsyntaxhighlight lang="ruby">func div_check(a, b){
Perl.eval("#{a} / #{b}")
}
 
say div_check(10, 2) # 5
say div_check(1, 0) # nil (detected)</langsyntaxhighlight>
 
=={{header|Slate}}==
<langsyntaxhighlight lang="slate">[ 1 / 0 ] on: Error do: [|:err| err return: PositiveInfinity].</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
Line 2,123 ⟶ 2,264:
 
{{works with|Smalltalk/X}}
<langsyntaxhighlight lang="smalltalk">|didDivideByZero a b|
 
didDivideByZero := false.
Line 2,136 ⟶ 2,277:
didDivideByZero ifTrue:[
Transcript show:'bad bad bad, but I already told you in the handler'.
].</langsyntaxhighlight>
Note: works in all Smalltalks: printf is available in the public domain printfScanf package (or already included in your dialect).
 
Line 2,142 ⟶ 2,283:
{{works with|Squeak}}
{{works with|Smalltalk/X}}
<langsyntaxhighlight lang="smalltalk">testZeroDivide :=
[:aBlock |
[
Line 2,152 ⟶ 2,293:
"Testing"
testZeroDivide value: [2/1] "------> false"
testZeroDivide value: [2/0] "------> true"</langsyntaxhighlight>
 
of course, as ZeroDivide inherits from Error, you could also write <langsyntaxhighlight lang="smalltalk">[...] on:Error do: [...]</langsyntaxhighlight>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}}
<langsyntaxhighlight lang="smalltalk">|a b result|
a := 10. b := 0.
result := [a / b] on:ZeroDivide do:[:ex | ex proceedWith:Float infinity].
Transcript showCR:result.</langsyntaxhighlight>
will show "inf" on the console window.
 
Line 2,171 ⟶ 2,312:
Using setexit( ) to trap and ignore division by zero.
<langsyntaxhighlight SNOBOL4lang="snobol4"> define('zdiv(x,y)') :(zdiv_end)
zdiv &errlimit = 1; setexit(.ztrap)
zdiv = x / y :(return)
Line 2,183 ⟶ 2,324:
output = '1.0/0.0 = ' zdiv(1.0,0.0) ;* Reals zero
output = 'Zero checks complete'
end</langsyntaxhighlight>
 
Output:
Line 2,195 ⟶ 2,336:
{{works with|Db2 LUW}} version 9.7 or higher.
With SQL PL:
<langsyntaxhighlight lang="sql pl">
--#SET TERMINATOR @
 
Line 2,218 ⟶ 2,359:
VALUES DIVISION(10, 3)@
VALUES DIVISION(10, 0)@
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,256 ⟶ 2,397:
=={{header|Standard ML}}==
Detection on integers by catching an exception:
<langsyntaxhighlight lang="sml">fun div_check (x, y) = (
ignore (x div y);
false
) handle Div => true</langsyntaxhighlight>
 
Detection on floats by checking for infiniteness:
<langsyntaxhighlight lang="sml">fun div_check (x, y) =
not (Real.isFinite (x / y))</langsyntaxhighlight>
 
=={{header|Stata}}==
Line 2,269 ⟶ 2,410:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc div_check {x y} {
if {[catch {expr {$x/$y}} result] == 0} {
puts "valid division: $x/$y=$result"
Line 2,283 ⟶ 2,424:
foreach denom {1 0 foo} {
div_check 42 $denom
}</langsyntaxhighlight>
{{out}}
<pre>valid division: 42/1=42
Line 2,291 ⟶ 2,432:
 
It is easier to trap such errors in Tcl 8.6, which has an additional control structure for exception processing:
<langsyntaxhighlight lang="tcl">proc div_check {x y} {
try {
puts "valid division: $x/$y=[expr {$x/$y}]"
Line 2,305 ⟶ 2,446:
foreach {num denom} {42 1 42 0 42.0 0.0 0 0 0.0 0.0 0 foo} {
div_check $num $denom
}</langsyntaxhighlight>
which produces the {{out}}
<pre>valid division: 42/1=42
Line 2,317 ⟶ 2,458:
=={{header|TXR}}==
 
<langsyntaxhighlight lang="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))</langsyntaxhighlight>
 
Run:
Line 2,332 ⟶ 2,473:
=={{header|Ursa}}==
{{trans|Python}}
<langsyntaxhighlight lang="ursa">def div_check (int x, int y)
try
/ x y
Line 2,339 ⟶ 2,480:
return true
end try
end</langsyntaxhighlight>
 
=={{header|VAX Assembly}}==
<langsyntaxhighlight VAXlang="vax Assemblyassembly">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
Line 2,357 ⟶ 2,498:
$ run dv
divide by zero
</syntaxhighlight>
</lang>
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">
<lang vb>
Option Explicit
 
Line 2,374 ⟶ 2,515:
If Err = 0 Then CatchDivideByZero = True
On Error GoTo 0
End Function</langsyntaxhighlight>
{{Out}}
<pre>Error
Line 2,380 ⟶ 2,521:
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
Function div(num,den)
On Error Resume Next
Line 2,394 ⟶ 2,535:
WScript.StdOut.WriteLine div(6,0)
WScript.StdOut.WriteLine div(7,-4)
</syntaxhighlight>
</lang>
 
{{Out}}
Line 2,405 ⟶ 2,546:
=={{header|Visual Basic .NET}}==
{{works with|Visual Basic .NET|9.0+}}
<langsyntaxhighlight lang="vbnet">Module DivByZeroDetection
 
Sub Main()
Line 2,420 ⟶ 2,561:
End Function
End Module
</syntaxhighlight>
</lang>
{{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}}==
<langsyntaxhighlight ecmascriptlang="wren">var checkDivByZero = Fn.new { |a, b|
var c = a / b
if (c.isInfinity || c.isNan) return true
Line 2,436 ⟶ 2,629:
System.print(" 0 / 0 -> %(checkDivByZero.call(0, 0))")
System.print(" 1 / 0 -> %(checkDivByZero.call(1, 0))")
System.print(" 1 / 1 -> %(checkDivByZero.call(1, 1))")</langsyntaxhighlight>
 
{{out}}
Line 2,454 ⟶ 2,647:
zero".
 
<langsyntaxhighlight XPL0lang="xpl0">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");
]</langsyntaxhighlight>
 
=={{header|Yorick}}==
 
<langsyntaxhighlight lang="yorick">func div_check(x, y) {
if(catch(0x01))
return 1;
temp = x/y;
return 0;
}</langsyntaxhighlight>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn f(x,y){try{x/y}catch(MathError){println(__exception)}}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,479 ⟶ 2,672:
MathError(INF (number is infinite))
</pre>
{{omit from|6502 Assembly|No hardware division}}
 
{{omit from|8080 Assembly|No hardware division}}
{{omit from|ACL2}}
{{omit from|AWK|Division by zero is always a fatal error.}}
Line 2,485 ⟶ 2,679:
{{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|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|sed|No division.}}
{{omit from|Swift|Division by zero is always a fatal error}}
{{omit from|Z80 Assembly|No hardware division}}
885

edits