Exception Handling and Error Reporting
Exception and Error handling
try..catch blocks can be used to control the flow of a program where Exceptions may be thrown. They can be caught and handled gracefully rather than letting PHP stop when one is encountered:
The above example would
catch the Exception thrown in the
try block and log it's message ("My test exception!") to a text file.
Catching different Exception types
You can implement multiple
catch statements for different types of exceptions to be handled in different ways, for example:
In the above example the first
catch will be used since it matches first in the order of execution. If you swapped the order of the
catch statements around, the
Exception catcher would execute first.
Similarly, if you were to throw an
UnexpectedValueException instead you would see the second handler for a standard
Exception being used.
If you need something to be done after either a
try or a
catch has finished running, you can use a
The above example would output the following:
Uh oh! Hello world - I'm finished now - home time!
In PHP 7 we see the introduction of the
Throwable interface, which
Error as well as
Exception implements. This adds a service contract level between exceptions in PHP 7, and allows you to implement the interface for your own custom exceptions:
Prior to PHP 7 you can simply typehint
Exception since as of PHP 5 all exception classes extend it.
Logging fatal errors
In PHP, a fatal error is a kind of error that cannot be caught, that is, after experiencing a fatal error a program does not resume. However, to log this error or somehow handle the crash you can use
register_shutdown_function to register shutdown handler.
Setting error reporting and where to display them
If it's not already done in php.ini, error reporting can be set dynamically and should be set to allow most errors to be shown:
errors will be logged by default by php, normally in a error.log file at the same level than the running script.
in development environment, one can also show them on screen:
in production however, one should
and show a friendly problem message through the use of an Exception or Error handler.