Fatal error handling in php 7

Published On: 14 April 2017.By .
  • Digital Engineering

Error / Exception handling is most important part of any php project. There was no way to handle fatal errors in the php  in the previous versions like 5.x.  In php 7, we can handle fatal errors by Error class.

Exceptions thrown from fatal and recoverable errors do not extend Exception class. This separation was made to prevent existing PHP 5.x code from catching exceptions thrown from errors that used to stop script execution. Exceptions thrown from fatal and recoverable errors are instances of a new and separate exception class: Error. Like any other exception, Error may be caught and handled and will allow any finally blocks to be executed.

Error is the base class for all internal PHP errors.

E.g. to handle fatal error.

Usually an object of the base Error class is thrown from previously fatal errors, but some errors will throw a more specific subclass of Error: TypeError, ArithmeticError, and AssertionError.

TypeError

A TypeError instance is thrown when a function argument or return value does not match a type declaration.

ArithmeticError

An ArithmeticError is thrown in two situations: bit shifting by a negative number or calling intdiv() with a numerator of PHP_INT_MIN and denominator of -1 (the expression using the division (/) operator, PHP_INT_MIN / -1, will return a float).

AssertionError

When the condition set by assert() is not met, an AssertionError will be thrown.

assert() is only executed and will only throw an AssertionError if assertions are enabled and set to throw exceptions with ini settings zend.assertions = 1 and assert.exception = 1.

Error class in your code

Developers are able to create Error as well as extend Error to create your own hierarchy of Error classes. This poses an important question: what situations should throw an instance of a class extending Exception and what situations should throw an instance of a class extending Error?

Error should be used to represent coding issues that require the attention of a programmer. Error objects thrown from the PHP engine fall into this category, as they generally result from coding errors such as providing a parameter of the wrong type to a function or a parse error in a file. Exception should be used for conditions that can be safely handled at runtime where another action can be taken and execution can continue.

Since Error objects should not be handled at runtime, catching Error objects should be uncommon. In general, Error objects should only be caught for logging, performing any necessary cleanup, and display an error message to the user.

Related content

That’s all for this blog