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.
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.
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();
}
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.
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;