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