Detect division by zero: Difference between revisions
→{{header|langur}}
Puppydrum64 (talk | contribs) No edit summary |
Langurmonkey (talk | contribs) |
||
(28 intermediate revisions by 14 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">
1 0 n:/ Inf? . cr
</syntaxhighlight>
{{out}}<pre>true</pre>
=={{header|ABAP}}==
<
data x type i.
try.
Line 24 ⟶ 26:
write 'Divide by zero.'.
endtry.
</syntaxhighlight>
=={{header|Ada}}==
<
with Ada.Text_Io; use Ada.Text_Io;
Line 58 ⟶ 60:
end if;
New_Line;
end Divide_By_Zero;</
{{out}}
<pre>
Line 66 ⟶ 68:
=={{header|Aime}}==
<
divide(integer n, integer d)
{
Line 86 ⟶ 88:
return 0;
}</
{{out}}
Line 114 ⟶ 116:
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}}
<
put(stand error, ("Exception: ",args, newline));
stop
Line 139 ⟶ 141:
raise zero division error := a different handler;
print(x/y)
END</
{{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.
<
% 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.</
=={{header|Arturo}}==
<
else -> print "division by zero" </
{{out}}
Line 188 ⟶ 190:
=={{header|AutoHotkey}}==
<
If ((num1/num2) != "")
MsgBox % num1/num2
Line 195 ⟶ 197:
}
ZeroDiv(0, 3) ; is ok
ZeroDiv(3, 0) ; divize by zero alert</
=={{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
<
110 ONERR GOTO 200
120 D = - 44 / 0
Line 213 ⟶ 215:
240 CALL - 3288: REM RECOVER
250 PRINT "DIVISION BY ZERO"
</syntaxhighlight>
==={{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}}===
<
PROCdivide(-44, 5)
PROCdivide(0, 5)
Line 234 ⟶ 248:
ENDCASE
ENDIF
ENDPROC</
==={{header|GW-BASIC}}===
The [[#Locomotive_BASIC|Locomotive BASIC]] solution works without any changes.
==={{header|IS-BASIC}}===
<
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</
==={{header|Liberty BASIC}}===
<
Function DetectDividebyZero(a, b)
Line 259 ⟶ 275:
Notice "Divide by Zero Detected!"
End If
End Function</
==={{header|Locomotive Basic}}===
<
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</
{{out}}
Line 274 ⟶ 290:
Division by zero in line 40 </pre>
==={{header|
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'''
<
Procedure MyErrorHandler()
Define txt$="The following error happened."+#CRLF$+ ErrorMessage()+"at line "+Str(ErrorLine())
Line 310 ⟶ 328:
Repeat
A=Random(100)/Random(100)
ForEver</
[[Image:OnError.png]]
'''With Floats, and without OnError library'''
<
Debug a/b</
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}}===
<
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</
==={{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}}==
<
set /a dummy=5/0 2>nul
if %errorlevel%==1073750993 echo I caught a division by zero operation...
exit /b 0</
=={{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}}==
Line 349 ⟶ 404:
Some systems will raise SIGFPE if a program divides by zero.
<
#include <setjmp.h> /* siglongjmp(), sigsetjmp() */
#include <stdio.h> /* perror(), printf() */
Line 448 ⟶ 503:
try_division(INT_MIN, -1);
return 0;
}</
{{out}} using OpenBSD/amd64:
Line 463 ⟶ 518:
The floating point types (float, double) don't raise an exception, but return the values Infinity or NaN as appropriate.
<
namespace RosettaCode {
Line 478 ⟶ 533:
}
}
}</
=={{header|C++}}==
<
#include<iostream>
#include<csignal> /* for signal */
Line 505 ⟶ 560:
return 0;
}
</syntaxhighlight>
=={{header|Ceylon}}==
<
//integers divided by zero throw an exception
Line 519 ⟶ 574:
//floats divided by zero produce infinity
print(1.0 / 0 == infinity then "division by zero!" else "not division by zero!");
}</
=={{header|Clojure}}==
Line 526 ⟶ 581:
return +inf, if 0, NaN, otherwise -inf.
<
(try (/ x y)
(catch ArithmeticException _
Line 532 ⟶ 587:
(cond (> x 0) Double/POSITIVE_INFINITY
(zero? x) Double/NaN
:else Double/NEGATIVE_INFINITY) )))</
=={{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}}==
<
ON SIZE ERROR
DISPLAY "Division by zero detected!"
END-DIVIDE</
=={{header|Common Lisp}}==
<
(division-by-zero () (format t "division by zero caught!~%")))</
=={{header|D}}==
<
string divCheck(T)(in T numer, in T denom)
Line 598 ⟶ 692:
divCheck(real.infinity, real.infinity));
writefln("real nan/ nan: %s", divCheck(real.nan, real.nan));
}</
{{out}}
<pre>Division with check:
Line 619 ⟶ 713:
=={{header|Delphi}}==
<
{$APPTYPE CONSOLE}
Line 636 ⟶ 730:
Writeln(e.Message);
end;
end.</
=={{header|Déjà Vu}}==
<
true
try:
Line 649 ⟶ 743:
!print "Okay"
else:
!print "Division by zero"</
{{out}}
<pre>Division by zero</pre>
Line 655 ⟶ 749:
=={{header|E}}==
<
def floatQuotient := numerator / denominator
if (floatQuotient.isNaN() || floatQuotient.isInfinite()) {
Line 662 ⟶ 756:
return ["ok", floatQuotient]
}
}</
=={{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 668 ⟶ 774:
Evaluate to zero - default behavior
<syntaxhighlight lang="ecl">
DBZ(REAL8 Dividend,INTEGER8 Divisor) := Quotient/Divisor;
#option ('divideByZero', 'zero');
DBZ(10,0); //returns 0.0
</syntaxhighlight>
Stop and report a division by zero error:
<syntaxhighlight 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>
Returns "nan":
<syntaxhighlight lang="ecl">
DBZ(REAL8 Dividend,INTEGER8 Divisor) := Quotient/Divisor;
#option ('divideByZero', 'nan');
Line 691 ⟶ 797:
Integer and decimal division by zero continue to return 0.
*/
</syntaxhighlight>
=={{header|Eiffel}}==
Line 697 ⟶ 803:
In a file called main.e:
<
creation main
feature main is
Line 717 ⟶ 823:
retry
end
end</
Note: The "rescue" statement catches ''every'' exception.
=={{header|Ela}}==
<
x /. y = try Some (x `div` y) with
_ = None
(12 /. 2, 12 /. 0)</
Output:
Line 735 ⟶ 841:
Of course the cleanest way to implement the safe division function is through pattern matching:
<
x /. y = Some (x / y)</
But it doesn't satisfy the task.
=={{header|Elixir}}==
<
def by_zero?(x,y) do
try do
Line 755 ⟶ 861:
|> Enum.each(fn {x,y} ->
IO.puts "#{x} / #{y}\tdivision by zero #{Division.by_zero?(x,y)}"
end)</
{{out}}
Line 772 ⟶ 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"].
<
(/ 1 0)
(arith-error
(message "Divide by zero (either integer or float)")))</
=={{header|Erlang}}==
<
case catch X/Y of
{'EXIT',_} -> true;
_ -> false
end.</
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
PROGRAM DIV_BY_ZERO
Line 796 ⟶ 902:
PRINT(3/0)
END PROGRAM
</syntaxhighlight>
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 806 ⟶ 912:
=={{header|F_Sharp|F#}}==
<
try
Some(x / y)
Line 814 ⟶ 920:
printfn "12 divided by 3 is %A" (detectDivideZero 12 3)
printfn "1 divided by 0 is %A" (detectDivideZero 1 0)</
Output:
Line 821 ⟶ 927:
=={{header|Factor}}==
<
: try-div ( a b -- )
'[ { +fp-zero-divide+ } [ _ _ /f . ] with-fp-traps ] try ;</
( scratchpad ) 1 2 try-div
Line 834 ⟶ 940:
=={{header|Fancy}}==
<
try {
x / y
Line 841 ⟶ 947:
}
}
</syntaxhighlight>
=={{header|Forth}}==
<
['] / catch -55 = if cr ." divide by zero!" 2drop 0 then ;</
=={{header|Fortran}}==
Line 852 ⟶ 958:
Floating-point division by zero detection.
<
program rosetta_divbyzero
implicit none
Line 894 ⟶ 1,000:
end program rosetta_divbyzero
</syntaxhighlight>
Integer division by zero. No detection.
<
program rosetta_integer_divbyzero
implicit none
Line 907 ⟶ 1,013:
write(*,*) answer
end program rosetta_integer_divbyzero
</syntaxhighlight>
=={{header|FreeBASIC}}==
Line 918 ⟶ 1,024:
The following code relies on this 'hack':-
<
Const divByZeroResult As Integer = -9223372036854775808
Line 942 ⟶ 1,048:
Print
Print "Press any key to exit"
Sleep</
{{out}}
Line 954 ⟶ 1,060:
=={{header|FutureBasic}}==
Stop on error. Error type reported in log console.
<
on error stop
print a / 0
HandleEvents
</syntaxhighlight>
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=6c837b97d9c5f296ef23245706544bdf Click this link to run this code]'''
<
Try Print 1 / 0
If Error Then Print Error.Text
End</
Output:
<pre>
Line 977 ⟶ 1,083:
=={{header|Go}}==
Detection on integers by recovering from a panic:
<
import "fmt"
Line 992 ⟶ 1,098:
fmt.Println(divCheck(3, 2))
fmt.Println(divCheck(3, 0))
}</
Output:
<pre>
Line 1,001 ⟶ 1,107:
=={{header|Groovy}}==
In Groovy, the float and double types follow IEEE numeric formats and rules. Here is a solution for double:
<
assert ! n.infinite : 'Algorithm fails if the numerator is already infinite.'
(n/d).infinite || (n/d).naN
}</
Test program:
<
((2d)..(0d)).each { j ->
println "${i}/${j} divides by zero? " + dividesByZero(i,j)
}
}</
Output:
Line 1,028 ⟶ 1,134:
=={{header|Haskell}}==
<
check x y = C.catch (x `div` y `seq` return False)
(\_ -> return True)</
=={{header|hexiscript}}==
<
let b 0
if tostr (a / (b + 0.)) = "inf"
Line 1,039 ⟶ 1,145:
else
println a / b
endif</
=={{header|HicEst}}==
<
XEQ( num// "/" // denom, *99) ! on error jump to label 99
zero_divide = 0 ! division OK
Line 1,048 ⟶ 1,154:
99 zero_divide = 1
END</
<
zero_divide( 1, 3-2-1 ) returns 1 (true)</
=={{header|HolyC}}==
HolyC throws <code>Except:DivZero</code>.
<
Print("%d\n", 10 / 0);
} catch {
Print("Divide by zero");
}</
=={{header|i}}==
<
concept IsDivisionByZero(a, b) {
c = a/b
Line 1,075 ⟶ 1,181:
IsDivisionByZero(5, 2)
IsDivisionByZero(0, 0)
}</
=={{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
<
&error := 1
udef := 1 / 0 | stop("Run-time error ", &errornumber, " : ", &errortext," in line #",&line," - converted to failure")
end</
Sample Output:<pre>Run-time error 201 : division by zero in line #3 - converted to failure</pre>
Line 1,088 ⟶ 1,194:
=={{header|IDL}}==
<
=={{header|J}}==
Line 1,099 ⟶ 1,205:
So, anyways, the task:
<
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,105 ⟶ 1,211:
Examples:
<
1.5
3 funnydiv 0
Line 1,114 ⟶ 1,220:
0
2 3 4 funnydiv 5
0.4 0.6 0.8</
=={{header|Java}}==
Line 1,120 ⟶ 1,226:
One way to do this check in Java is to use the <tt>isInfinite</tt> function from the <tt>Double</tt> class:
<
return Double.isInfinite(numer/denom);
}</
Another way is to use the <tt>ArithmeticException</tt> as a check (which is not preferred because it expects an exception):
<
try{
int dummy = (int)numer / (int)denom;//ArithmeticException is only thrown from integer math
return false;
}catch(ArithmeticException e){return true;}
}</
=={{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):
<
{
var quotient=dividend/divisor;
Line 1,139 ⟶ 1,245:
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 "==".
Line 1,146 ⟶ 1,252:
We can however define div(x;y) so that it raises an error, "NaN", if y equals 0:
<
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</
=={{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:
<
=={{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.
<
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</
{{out}}
Line 1,172 ⟶ 1,278:
=={{header|Kotlin}}==
<
fun divideByZero(x: Int, y:Int): Boolean =
Line 1,191 ⟶ 1,297:
println("$x / $y = ${x / y}")
}
}</
{{out}}
Line 1,201 ⟶ 1,307:
Thanks to Javascript a division by zero doesn't throw an error, just the word "Infinity".
<
{def DivByZero?
{lambda {:w}
Line 1,210 ⟶ 1,316:
{DivByZero? {/ 3 0}}
-> true
</syntaxhighlight>
=={{header|LabVIEW}}==
Line 1,216 ⟶ 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}}==
<
(
#a->isNotA(::integer) && #a->isNotA(::decimal) ||
Line 1,230 ⟶ 1,358:
}
dividehandler(1,0)</
{{out}}
Line 1,236 ⟶ 1,364:
=={{header|Lingo}}==
<
-- for simplicity type check of vars omitted
res = value("float(a)/b")
Line 1,244 ⟶ 1,372:
return res
end if
end</
=={{header|Lua}}==
Lua, like Javascript, does not error on DIVIDE-BY-ZERO, but returns infinity, -infinity or -nan. So:
<
if b == 0 then error() end
return a/b
end</
=={{header|M2000 Interpreter}}==
Line 1,258 ⟶ 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">
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()) {
Line 1,284 ⟶ 1,412:
}
Checkit
</syntaxhighlight>
=={{header|M4}}==
<
Output, with standard output labeled "==>" and error output labeled "error==>":
Line 1,297 ⟶ 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.
<
Output:
<pre>Error, numeric exception: division by zero</pre>
Here is a simple custom handler being installed and used.
<
= proc() infinity; end proc ):
1/0;
NumericStatus(':-division_by_zero'); # We may check the status flag</
Output:
<pre> infinity
Line 1,312 ⟶ 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.
<
= proc()
WARNING("division by zero");
Line 1,321 ⟶ 1,449:
1/0;
NumericStatus(':-division_by_zero');</
Output:
<pre>Warning, division by zero
Line 1,329 ⟶ 1,457:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
=={{header|MATLAB}}==
<
isDividedByZero = isinf( numerator/denomenator );
% If isDividedByZero equals 1, divide by zero occured.</
=={{header|Maxima}}==
<
f(5, 6);
Line 1,343 ⟶ 1,471:
f(5, 0;)
'error</
=={{header|MAXScript}}==
<
=={{header|min}}==
{{works with|min|0.19.3}}
The following operator will detect division by zero since the result will be infinity.
<
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}}==
<
if ($calc(1/ %n) == $calc((1/ %n)+1)) {
echo -ag Divides By Zero
Line 1,361 ⟶ 1,525:
else {
echo -ag Does Not Divide By Zero
}</
=={{header|MUMPS}}==
<
;The ANSI error code for division by zero is "M9".
;$ECODE errors are surrounded by commas when set.
Line 1,374 ⟶ 1,538:
DIVFIX
IF $FIND($ECODE,",M9,")>1 WRITE !,"Error: Division by zero" SET $ECODE="" QUIT ""
QUIT "" ; Fall through for other errors</
Output:<pre>
USER>W $$DIV^ROSETTA(1,2)
Line 1,391 ⟶ 1,555:
=={{header|Nanoquery}}==
<
try
(x / y)
Line 1,398 ⟶ 1,562:
return true
end
end</
=={{header|Neko}}==
Float, non-float as infinity and catching an $idiv. *Not demonstrated in a function.*
<syntaxhighlight lang="actionscript">/**
Detect division by zero
*/
Line 1,413 ⟶ 1,577:
if $isinfinite(ans) $print("division by zero: ", ans, "\n")
try $print($idiv(1, 0)) catch problem $print("idiv by zero: ", problem, "\n")</
{{out}}
Line 1,424 ⟶ 1,588:
=={{header|NetLogo}}==
<
;; 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,446 ⟶ 1,610:
]
[ output-print (word a " / " b " is not calculable"
]</
=={{header|NetRexx}}==
<
options replace format comments java crossref symbols nobinary
Line 1,472 ⟶ 1,636:
say dividend '/' divisor '=' divide(dividend, divisor)
return
</syntaxhighlight>
Output:
<pre>netrexx.lang.DivideException: Divide by 0
Line 1,481 ⟶ 1,645:
=={{header|NewLISP}}==
<
(define (check-division x y)
Line 1,495 ⟶ 1,659:
(println (check-division 11 0))
(exit)</
Output:
Line 1,515 ⟶ 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.
<
proc divCheck(x, y): bool =
try:
Line 1,524 ⟶ 1,688:
{.pop.} # Restore default check settings
echo divCheck(2, 0)</
=={{header|NS-HUBASIC}}==
<
20 PRINT 1/0
30 END
40 IF ERR = 10 THEN PRINT "DIVISION BY ZERO IN LINE"ERL
50 RESUME 30</
=={{header|OCaml}}==
Detection on integers by catching an exception:
<
try
ignore (x / y);
false
with Division_by_zero ->
true</
Detection on floats by checking for infiniteness:
<
classify_float (x /. y) = FP_infinite</
=={{header|Octave}}==
Line 1,550 ⟶ 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.
<
if ( isinf(d) )
if ( index(lastwarn(), "division by zero") > 0 )
error("division by zero")
endif
endif</
=={{header|Oforth}}==
<
| e |
try: e [ 128 n / ] when: [ "Zero detected..." . ]
"Leaving" println ;</
=={{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!
<
(define (safediv a b)
(if (eq? (type b) type-complex)
Line 1,585 ⟶ 1,749:
(safediv 5 7/5) ; => 25/7
))
</syntaxhighlight>
=={{header|ooRexx}}==
<
* program demonstrates detects and handles division by zero.
* translated from REXX:
Line 1,605 ⟶ 1,769:
Say sourceline(sigl)
Say 'rc='rc '('errortext(rc)')'
Exit 12</
Output:
<pre>Syntax raised in line 11
Line 1,613 ⟶ 1,777:
=={{header|Oz}}==
For integer division only.
<
{Show 42 div 0}
catch error(kernel(div0 ...) ...) then
{System.showInfo "Division by zero detected."}
end</
=={{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.
<
err,
print("division by 0"); print("or other non-invertible divisor"),
errname(err) == "e_INV");</
Or the previous <code>trap()</code>,
<
=={{header|Pascal}}==
Line 1,636 ⟶ 1,800:
=={{header|Perl}}==
This function returns true iff its second argument is zero.
<
{local $@;
eval {$_[0] / $_[1]};
$@ and $@ =~ /division by zero/;}</
=={{header|Phix}}==
{{libheader|Phix/basics}}
<!--<
<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,650 ⟶ 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;">)
<!--</
{{out}}
<pre>
Line 1,659 ⟶ 1,823:
=={{header|PHP}}==
This function returns true iff its second argument is zero.
<
@trigger_error(''); // a dummy to detect when error didn't occur
@($x / $y);
$e = error_get_last();
return $e['message'] != '';
}</
<
return @($x / $y) === FALSE; // works at least in PHP/5.2.6-3ubuntu4.5
}</
=={{header|PicoLisp}}==
<
=={{header|PL/I}}==
<
Dcl (a,b,c) Float Bin(33);
On ZeroDivide GoTo MyError;
Line 1,683 ⟶ 1,847:
End DivideDZ;
xx=DivideDZ(1,0);</
=={{header|PL/SQL}}==
<
RETURN BOOLEAN
IS
Line 1,696 ⟶ 1,860:
WHEN ZERO_DIVIDE THEN
RETURN(true);
end divide;</
<
divide(1,0) --true, division by zero</
=={{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">
function div ($a, $b) {
try{$a/$b}
Line 1,709 ⟶ 1,889:
div 10 2
div 1 0
</syntaxhighlight>
{{Out}}
<pre>
Line 1,717 ⟶ 1,897:
=={{header|Prolog}}==
<
div(A, B, C, Ex) :-
catch((C is A/B), Ex, (C = infinity)).
</syntaxhighlight>
{{Out}}
<pre>
Line 1,734 ⟶ 1,914:
Floating point division yields inf or nan values as appropriate (if the FPU supports IEEE 754):
<
inf,-inf,nan</
It's possible to check for these values as follows:
<
> 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 0 1;
0
> divide 1 0;
"divide by 0"</
=={{header|Python}}==
<
try:
x / y
Line 1,758 ⟶ 1,938:
return True
else:
return False</
=={{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>).
<
?[1=sum r=(0n;0w;-0w);"division by zero detected";()]</
=={{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:
<
if ( !is.finite(d) ) {
# it is Inf, -Inf, or NaN
}</
=={{header|Racket}}==
Line 1,777 ⟶ 1,957:
In Racket, the division by zero exception can be caught directly:
<
#lang racket
Line 1,783 ⟶ 1,963:
(λ (e) (displayln "Divided by zero"))])
(/ 1 0))
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
====Try/Catch====
<syntaxhighlight lang="raku"
my $r;
try {
Line 1,799 ⟶ 1,979:
}
say div(10,2);
say div(1, sin(0));</
{{out}}
<pre>5
Line 1,806 ⟶ 1,986:
====Multi Method Dispatch====
<syntaxhighlight lang="raku"
multi div($a, $b where { $b == 0 }) { note 'Attempt to divide by zero.'; return Nil }
say div(10, 2);
say div(1, sin(0));</
{{out}}
<pre>5
Line 1,817 ⟶ 1,997:
=={{header|REBOL}}==
<
Title: "Detect Divide by Zero"
URL: http://rosettacode.org/wiki/Divide_by_Zero_Detection
Line 1,843 ⟶ 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.</
Output:
Line 1,855 ⟶ 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.
<
signal on syntax /*handle all REXX syntax errors. */
x = sourceline() /*being cute, x=is the size of this pgm*/
Line 1,877 ⟶ 2,057:
/*──────────────────────────────────────────────────────────────────────────────────────*/
syntax: @=sigl; call err 'REXX program' condition("C") 'error', condition('D'), ,
'REXX source statement (line' sigl"):", sourceLine(sigl)</
{{out|output|text=}}
<pre>
Line 1,886 ⟶ 2,066:
=={{header|Ring}}==
<
Try
see 9/0
Line 1,892 ⟶ 2,072:
see "Catch!" + nl + cCatchError
Done
</syntaxhighlight>
=={{header|RPGIV}}==
<
dcl-c DIVIDE_BY_ZERO 00102;
Line 1,913 ⟶ 2,093:
*inlr = *on;
</syntaxhighlight>
=={{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.
<
begin
x / y
Line 1,926 ⟶ 2,121:
false
end
end</
Ruby allows division by zero if either operand is a Float.
<
=> true
irb(main):011:0> div_check(5.0, 0)
=> false</
----
Line 1,941 ⟶ 2,136:
{{works with|Ruby|1.9}}
<
begin
x.div y
Line 1,949 ⟶ 2,144:
false
end
end</
<
=> true
irb(main):011:0> div_check(5.0, 0)
=> true</
=={{header|Rust}}==
<
match numerator.checked_div(denominator) {
Some(result) => println!("{} / {} = {}", numerator, denominator, result),
Line 1,967 ⟶ 2,162:
test_division(5, 4);
test_division(4, 0);
}</
=={{header|Scala}}==
Line 1,973 ⟶ 2,168:
as it is not needed. The method would get optimized to
always return false.
<
def check(x: Int, y: Int): Boolean = {
Line 1,995 ⟶ 2,190:
println("divided by zero = " + check1(1, 0))
}</
=={{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.
<
include "float.s7i";
Line 2,031 ⟶ 2,226:
doDivide(10.0, 8.0);
doDivide(1.0, 0.0);
end func;</
Output:
Line 2,043 ⟶ 2,238:
=={{header|Sidef}}==
The numerical system of Sidef evaluates `x/0` to `+/-Inf`.
<
var result = a/b
result.abs == Inf ? nil : result
Line 2,049 ⟶ 2,244:
say div_check(10, 2) # 5
say div_check(1, 0) # nil (detected)</
Alternatively, we can do:
<
Perl.eval("#{a} / #{b}")
}
say div_check(10, 2) # 5
say div_check(1, 0) # nil (detected)</
=={{header|Slate}}==
<
=={{header|Smalltalk}}==
Line 2,069 ⟶ 2,264:
{{works with|Smalltalk/X}}
<
didDivideByZero := false.
Line 2,082 ⟶ 2,277:
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).
Line 2,088 ⟶ 2,283:
{{works with|Squeak}}
{{works with|Smalltalk/X}}
<
[:aBlock |
[
Line 2,098 ⟶ 2,293:
"Testing"
testZeroDivide value: [2/1] "------> false"
testZeroDivide value: [2/0] "------> true"</
of course, as ZeroDivide inherits from Error, you could also write <
You can also provide an alternative value from the exception handler:
{{works with|Smalltalk/X}}
<
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.
Line 2,117 ⟶ 2,312:
Using setexit( ) to trap and ignore division by zero.
<
zdiv &errlimit = 1; setexit(.ztrap)
zdiv = x / y :(return)
Line 2,129 ⟶ 2,324:
output = '1.0/0.0 = ' zdiv(1.0,0.0) ;* Reals zero
output = 'Zero checks complete'
end</
Output:
Line 2,141 ⟶ 2,336:
{{works with|Db2 LUW}} version 9.7 or higher.
With SQL PL:
<
--#SET TERMINATOR @
Line 2,164 ⟶ 2,359:
VALUES DIVISION(10, 3)@
VALUES DIVISION(10, 0)@
</syntaxhighlight>
Output:
<pre>
Line 2,202 ⟶ 2,397:
=={{header|Standard ML}}==
Detection on integers by catching an exception:
<
ignore (x div y);
false
) handle Div => true</
Detection on floats by checking for infiniteness:
<
not (Real.isFinite (x / y))</
=={{header|Stata}}==
Line 2,215 ⟶ 2,410:
=={{header|Tcl}}==
<
if {[catch {expr {$x/$y}} result] == 0} {
puts "valid division: $x/$y=$result"
Line 2,229 ⟶ 2,424:
foreach denom {1 0 foo} {
div_check 42 $denom
}</
{{out}}
<pre>valid division: 42/1=42
Line 2,237 ⟶ 2,432:
It is easier to trap such errors in Tcl 8.6, which has an additional control structure for exception processing:
<
try {
puts "valid division: $x/$y=[expr {$x/$y}]"
Line 2,251 ⟶ 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
}</
which produces the {{out}}
<pre>valid division: 42/1=42
Line 2,263 ⟶ 2,458:
=={{header|TXR}}==
<
(catch (/ x y)
(numeric_error (msg)
'div-check-failed))))
@(bind good @(div-check 32 8))
@(bind bad @(div-check 42 0))</
Run:
Line 2,278 ⟶ 2,473:
=={{header|Ursa}}==
{{trans|Python}}
<
try
/ x y
Line 2,285 ⟶ 2,480:
return true
end try
end</
=={{header|VAX Assembly}}==
<
6F 72 65 7A 20 79 62 20 000E
0000 0016 2 .entry handler,0
Line 2,303 ⟶ 2,498:
$ run dv
divide by zero
</syntaxhighlight>
=={{header|VBA}}==
<syntaxhighlight lang="vb">
Option Explicit
Line 2,320 ⟶ 2,515:
If Err = 0 Then CatchDivideByZero = True
On Error GoTo 0
End Function</
{{Out}}
<pre>Error
Line 2,326 ⟶ 2,521:
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
Function div(num,den)
On Error Resume Next
Line 2,340 ⟶ 2,535:
WScript.StdOut.WriteLine div(6,0)
WScript.StdOut.WriteLine div(7,-4)
</syntaxhighlight>
{{Out}}
Line 2,351 ⟶ 2,546:
=={{header|Visual Basic .NET}}==
{{works with|Visual Basic .NET|9.0+}}
<
Sub Main()
Line 2,366 ⟶ 2,561:
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}}==
<
var c = a / b
if (c.isInfinity || c.isNan) return true
Line 2,382 ⟶ 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))")</
{{out}}
Line 2,400 ⟶ 2,647:
zero".
<
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");
]</
=={{header|Yorick}}==
<
if(catch(0x01))
return 1;
temp = x/y;
return 0;
}</
=={{header|zkl}}==
<
{{out}}
<pre>
Line 2,425 ⟶ 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,431 ⟶ 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}}
|