Latest web development tutorials

PHP 7 Error Handling

PHP 7 New Features PHP 7 New Features

PHP 7 to change the wrong way most reports. Unlike traditional PHP error reporting mechanism 5, and now most of the errors are thrown as an exception Error.

This Error exception can be as normal as abnormal captured try / catch block. If no matching try / catch block, call the exception handler (() registered by the set_exception_handler) for processing. If you have not registered exception handler is processed in the traditional way: is reported as a fatal error (Fatal Error).

Error class does not extend out from the Exception class, so use catch (Exception $ e) {...} This code is not to capture the Error. You can catch Error with a catch (Error $ e) {...} This code, or by registered exception handler (set_exception_handler ()).

Error exception hierarchy

  • Error
    • ArithmeticError
    • AssertionError
    • DivisionByZeroError
    • ParseError
    • TypeError
  • Exception
    • ...

Examples

Examples

<? php
class MathOperations
{
protected $ n = 10;

// Remainder operation, the divisor is 0, an exception is thrown
public function doOperation (): string
{
try {
$ value = $ this -> n % 0;
return $ value;
} Catch (DivisionByZeroError $ e) {
return $ e -> getMessage () ;
}
}
}

$ mathOperationsObj = new MathOperations ();
print ($ mathOperationsObj -> doOperation ( ));
?>

The above program execution output is:

Modulo by zero

PHP 7 New Features PHP 7 New Features