Web dev

PHP 7 errors and exceptions

PHP 7 changes the way errors and exceptions are reported by PHP. There is a new Throwable base interface for any object that can be thrown via a throw statement.

Throwable

Below you can see the complete Throwable hierarchy:

  • Throwable
    • Exception
      • LogicException
        • BadFunctionCallException
          • BadMethodCallException
        • DomainException
        • InvalidArgumentException
        • LengthException
        • OutOfRangeException
      • RuntimeException
        • OutOfBoundsException
        • OverflowException
        • RangeException
        • UnderflowException
        • UnexpectedValueException
      • ErrorException
    • Error
      • ArithmeticError
        • DivisionByZeroError
      • AssertionError
      • ParseError
      • TypeError

The Throwable interface looks like that:

If you want to create your custom class you cannot implement the Throwable interface directly, you must extend the Exception class instead.

Below an example of extention:

 

Exceptions

The LogicException class is related to errors in the program logic that should raise a code fix.

A RuntimeException is thrown when an error is found when the program is running.

The ErrorException class is quite interesting and is mostly used to turn PHP errors in ErrorExceptions combined with set_error_handler(). The class includes a severity property for the “hardness” of the error raised.

In the new PHP 7.1 release can be possible to catch multiple exception in this way:

Errors

Most of the previous fatal and recoverable fatal errors in PHP 7 are thrown an instance of Error.

An ArithmeticError is thrown for error related to mathematical operations (i.e.: wrong intdiv() calls).

The AssertionError class covers failures made via the assert() function.

A ParseError is thrown when parsing the eval() function cause an error or in case of error in the include/require functions.

TypeErrors are related to the new introduction of scalar, and strict types in PHP 7 and may be thrown when the value or the type of a function argument does not match with the one declared, or an invalid number of arguments are passed (strict mode only).

Conclusion

If you are going to support PHP 7 be sure to catch any exception using multiple try/catch blocks. For a brand new project, you can maybe struggle to find what is the right exception to thrown, but you can easily create one by yourself.

If you want to check your project quickly, you can use one of the tools below:

Of course you can use the PHP documentation as a reference.

If you want to learn more about PHP 7, check out my new video course: “Learning PHP 7”

Leave a Comment