0

How can I handle an exception in PHP? As an example, in the code like this:

<?php
   $a=5;
   $b=0
   $c=($a/$b);
   echo $c;
?>

Please help me.

Francis M. Bacon
  • 665
  • 7
  • 20
Ripa Saha
  • 2,532
  • 6
  • 27
  • 51

3 Answers3

1

PHP raises warnings and error messages not by throwing an exception, therefore you cannot catch anything here. However, you can modify this behaviour:

// Register a custom error handler that throws an ErrorException
// whenever a warrning or error occurs
set_error_handler(function ($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
});

$a = 5;
$b = 0;

// Now a division by zero will result into an ErrorException being thrown
try {
    $c = $a / $b;
    echo $c;
} catch (ErrorException $e) {
    echo 'Error: ' . $e->getMessage();
}
Niko
  • 26,516
  • 9
  • 93
  • 110
  • it's working. but if you explain set_error_handler(function ($errno, $errstr, $errfile, $errline ) { throw new ErrorException($errstr, 0, $errno, $errfile, $errline); }); then it will clear my understanding.thanks. – Ripa Saha Feb 11 '13 at 10:47
  • This registers a custom error handler - by default, PHP will either log or print the error message to the screen. By registering a custom error handler, you tell PHP that you'd like to handle error messages differently. PHP then invokes the error handler instead of outputting the message. In this case, the error handler then throws an exception, i.e., it turns error messages into exceptions. – Niko Feb 11 '13 at 16:01
0

As far as I'm aware PHP will not throw an exception on division by zero. I tested 5.3, it triggers a warning and so would all lesser versions. So putting that in a try block wont do anything. You can map PHP Errors to Exceptions with the ErrorException class, and some screwing around with error and exception handlers. See https://github.com/sam-at-github/php_error_exceptions for a reference implementation of that screwing around.

spinkus
  • 7,694
  • 4
  • 38
  • 62
-1

First: you are doing a division at the second line code (which can be devision by zero).

Second: no need to return false in your method since you are throwing an error.

Third: Why using an exception here and not just let you method return true of false and check on that before executing the devision.

Fourth: Why having a method if you only need to check on the value of $y. Calling the method or including an if-statement requires both just one line of code.

So, why can't it just be like:

case '/':                  
    if($b > 0)
        $prod = $a / $b;
    break; 
Raj Adroit
  • 3,828
  • 5
  • 31
  • 44