PHP Errors in PHP7

PHPServer Side ProgrammingProgramming


Prior to version 7, PHP parser used to report errors in response to various conditions. Each error used to be of a certain predefined type. PHP7 has changed the mechanism of error reporting. Instead of traditional error reporting, most errors are now reported by throwing error exceptions.

If error exceptions go unhandled, a fatal error is reported and will be handled like traditional error condition. PHP's error heirarchy starts from Throwable interface. All predefined errors such as ArithmeticError, AssertionError, CompileError and TypeError are classes implementing Throwable iterface. Exception in PHP 7 is also implements Throwable interface.

Throwable interface acts as base for any object that can be thrown via throw statement, including Error and Exception objects. A user defined class can not implement Throwable interface directly. Instead, to declare a user defined exception class, it must extend Exception class.

PHP's exception handling consists of throw, catch, try statements. To raise exception object, there is throw keyword. Thrown exception are processed by catch block. PHP code that is potentially vulnerable for exception is enclosed in try block.

One or more catch blocks may be present to catch different instances of Exception classes. When no exception occurs in try block, normal execution will continue after last catch block. However, when exception is thrown inside try block, instead of nest statement being executed, PHP tries to find a catch block tht matches type of exception to be handled. If no matching catch block is defined, PHP parser will report Fatal error with Uncaught Exception message.

You may also provide finally block either after or instead of catch blocks. Code in finally block will always be executed, irresepective of whether exception occurs inside try block or not.

Published on 18-Sep-2020 08:57:16