Menu Close

Articles

PHP: Exception handling

PHP 7 has an exception model similar Java. An exception is an object that can be “thrown”, and “catch” using a “try” block. At this time I assume you have learned enough about classes and functions to comprehend this model.

Exceptions & Errors

An exception is a special class that you can use to create exception objects. Errors are similar to exceptions. Both Error and Exception classes are implementing a common interface: Throwable. 

  • errors are internal PHP errors,
  • exceptions are created by users. 

Fatal errors: such as running out of memory, will halt immediately the script execution and can not be handled. Also, any uncaught exception is considered a fatal error that will cause the script to stop.

Warning: PHP 5 has a different error model. 

Throwable

To unite the two exception classes, Exception and Error both implement a interface, Throwable. 

Type hierarchy 

In PHP 7.2 the type hierarchy was updated and it looks like this:

Pattern:

Throwable may be used in try/catch blocks to catch both Exception and Error objects: 

Note: 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.

Catching Exceptions

In practice exceptions objects are anonymous and thrown immediately after creation. It is uncommon to create a variable to hold exception object. Because of this the “catch” must give a name to the caught exception, that is called exception handler:

Example:

Note: Handler $e do not exist until the exception is caught.

Ensure execution

Sometimes our purpose is not to catch the exception but to ensure a piece of code is executed after specific code protected by try block. For this we use “finally” keyword associate with “try” statement.

Pattern:

Note: 

  • Mandatory code is executed all the time after protected code,
  • If the protected code fail, the mandatory code is still executed,
  • Previous design pattern do not use a “catch” block but it could.

Peculiar behavior

One of most bizarre feature of PHP is the execution of code after return statement. Using finally you can enforce a piece of code to be executed even after you have prepare a result using return statement:

Example:

Using exit() and die() 

These two functions can be used to stop script execution and create unrecoverable error. Function die() is the older version. Function exit() is a language construct so it can be called without brackets.

Example:

In previous code, function test() is interrupted before it return “done.” So instead of printing: “done.” it will exit and print “error!” instead. 

Output:  error!

Syntax for exit is overloaded. You can return an error code or a message:

Pattern:

Because “or” is a short-circuit operator, the following design pattern is possible and for some reason preferred by PHP developers: 

A better approach is to use a try block and catch the exception:

Example:

Note: proactive checking is considered good practice. catching errors must be done only when is necessary. However if you do not, you will get a warning message:

Error Reporting

By default all errors and warning messages are printed out into your output document. Even if you use a try-catch block, you can not suppress all messages that came out from a function call.

Example

Output:

PHP Warning: fopen(/path/to/data-file): failed to open stream: No such file or directory in index.php on line 5 File open failed.

The output message do not look right. I have expected: “File open failed.” But instead I got a long message starting with “PHP Warning:”. To suppress warnings you must use directive error_reporting.

error_reporting ( int $level  ) : int

Parameter $level is a bit-mask. It can be created using bitwise operators and predefined constants:

Example:

Output:

The warning message is gone:

File open failed.

Predefined constants:

  • E_ERROR
  • E_WARNING
  • E_PARSE
  • E_NOTICE
  • E_ALL (include all the above)

Examples:

Read next: File handling