Function DetectDividebyZero(a, b)OnErrorGoTo[Error] DetectDividebyZero=(a/ b)ExitFunction[Error]IfErr=11Then'11 is the error number raised when divide by zero occursNotice"Divide by Zero Detected!"EndIfEndFunction

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 ErrorProcedure 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 happensOnErrorCall(@MyErrorHandler())

;Now, do something very stupid so that we may see an Error...Repeat A=Random(100)/Random(100)ForEver

/* * 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. */staticvoidfpe_handler(int signal, siginfo_t *w,void*a){ siglongjmp(fpe_env, w->si_code);/* NOTREACHED */}

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.

/* 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.*/

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".

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_divbyzeroimplicitnoneinteger, parameter::rdp=kind(1.d0)real(rdp)::normal,zero

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).

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.

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))return0;//Can be changed to whatever is desired by the programmer to be 0, false, or Infinityreturn 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 "==".

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.

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.

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 DDIVFIX IF $FIND($ECODE,",M9,")>1 WRITE !,"Error: Division by zero" SET $ECODE="" QUIT "" QUIT "" ; Fall through for other errors

;; 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"]

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.

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.

; 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.

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.

This REXX program makes use of LINESIZE REXX program (or BIF) which is used to determine the screen width (or linesize) of the terminal (console).
The LINESIZE.REX REXX program is included here ──► LINESIZE.REX.

output

════════════════════════ division by zero is a no-no. ═════════════════════════

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.

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".