PHP Exceptions
PHP 5 provides a new object-oriented way of dealing with errors.
What Is an Exception
Exception handling is used to change the normal flow of the code execution if a specified error (exceptional) condition occurs.
This condition is called an exception.
This is what normally happens when an exception is triggered:
- The current code state is saved.
- The code execution will switch to a predefined (custom) exception handler function.
- Depending on the situation, the handler may then resume the execution from the saved code state, terminate the script execution or continue the script from a different location in the code.
†Exceptions should only be used with error conditions, and should not be used to jump to another place in the code at a specified point.
Basic Use of Exceptions
When an exception is thrown, the code following it will not be executed, and PHP will try to find the matching catch
block.
If an exception is not caught, a fatal error will be issued with an Uncaught Exception
message.
Proper exception code should include:
Try
:
A function using an exception should be in a try
block.
If the exception does not trigger, the code will continue as normal.
However if the exception triggers, an exception is “thrown.”
Throw
:
This is how you trigger an exception.
Each throw
must have at least one catch
.
Catch
:
A catch
block retrieves an exception and creates an object containing the exception information.