Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to suppress the "Division by zero" error and set the result to null for the whole application?

Tags:

php

How to suppress the "Division by zero" error and set the result to null for the whole application? By saying "for the whole application", I mean it is not for a single expression. Instead, whenever a "Division by zero" error occurs, the result is set to null automatically and no error will be thrown.

like image 815
Ethan Avatar asked Sep 16 '10 23:09

Ethan


People also ask

Which error type will result if you try to divide by zero in a program?

Definition. Division by zero is a logic software bug that in most cases causes a run-time error when a number is divided by zero.

How do you get rid of the divide by zero error in Python?

The Python "ZeroDivisionError: float division by zero" occurs when we try to divide a floating-point number by 0 . To solve the error, use an if statement to check if the number you are dividing by is not zero, or handle the error in a try/except block.

Which interrupt get generated when divide by zero error occur?

The operating system sets up the functions (interrupt handler, exception handler) for each event. When a divide by zero occurs, it triggers an exception. The CPU responds by invoking the exception handler in the interrupt vector corresponding to a divide by zero.


1 Answers

This should do the trick.

$a = @(1/0); 
if(false === $a) {
  $a = null;
}
var_dump($a);

outputs

NULL

See the refs here error controls.

EDIT

function division($a, $b) {
    $c = @(a/b); 
    if($b === 0) {
      $c = null;
    }
    return $c;
}

In any place substitute 1/0 by the function call division(1,0).

EDIT - Without third variable

function division($a, $b) {         
    if($b === 0)
      return null;

    return $a/$b;
}
like image 154
Igor Avatar answered Oct 09 '22 11:10

Igor