Detect division by zero: Difference between revisions

Updated to take in account the difference between errors and defects.
(Added Wren)
(Updated to take in account the difference between errors and defects.)
Line 1,471:
 
=={{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.
 
<lang nim>{.push overflowChecks: on.}
proc divCheck(x, y): bool =
try:
discard x div y
except DivByZeroErrorDivByZeroDefect:
return true
return false
Anonymous user