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:

Throwable interface

PHP

1

2

3

4

5

6

7

8

9

10

11

Throwable{

/* Methods */

abstractpublicstringgetMessage(void)

abstractpublicintgetCode(void)

abstractpublicstringgetFile(void)

abstractpublicintgetLine(void)

abstractpublicarraygetTrace(void)

abstractpublicstringgetTraceAsString(void)

abstractpublicThrowable getPrevious(void)

abstractpublicstring__toString(void)

}

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:

PHP

1

2

3

4

5

6

7

8

9

10

11

classMyCustomExceptionextendsException

{

publicfunction__construct($message,$code=0,Exception$previous=null){

//custom code

parent::__construct($message,$code,$previous);

}

publicfunction__toString(){

return__CLASS__.": [{$this->code}]: {$this->message}\n";

}

}

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:

PHP

1

2

3

4

5

6

7

try{

// to do something

}catch(FirstException|SecondException$e){

// Handle these exceptions

}catch(Exception$e){

// to do something

}

Errors

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

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: