PHP Exception Handling
Exceptions are used to change the normal flow of a script when a specified error occurs.
What is an Exception
PHP 5 provides a new object-oriented way of handling errors.
Exception handling is used to change the normal flow of a script when a specified error (exception) occurs. This situation is called an exception.
When an exception is triggered, typically the following happens:
- The current code state is saved
- Code execution is switched to a predefined (custom) exception handler function
- Depending on the situation, the handler may resume code execution from the saved code state, terminate script execution, or continue execution from another location in the code
We will demonstrate different error handling methods:
- Basic Usage of Exceptions
- Creating a Custom Exception Handler
- Multiple Exceptions
- Re-throwing an Exception
- Setting a Top-Level Exception Handler
**Note:** Exceptions should only be used in error situations, not for jumping to another location in the code at a specified point.
Basic Usage of Exceptions
When an exception is thrown, the code following it will not continue to execute; PHP will try to find a matching "catch" block.
If the exception is not caught, and set_exception_handler() is not used to handle it, then a serious error (fatal error) occurs, and the error message "Uncaught Exception" is output.
Let's try to throw an exception without catching it:
1 ) { throw new Exception ( " Value must be 1 or below " ) ; } return true ; } // trigger exception checkNum ( 2 ) ; ?>The code above will produce an error like this:
Fatal error: Uncaught exception 'Exception' with message 'Value must be 1 or below' in /www/runoob/test/test.php:7 Stack trace: #0 /www/runoob/test/test.php(13): checkNum(2) #1 {main} thrown in /www/runoob/test/test.php on line 7
Try, throw, and catch
To avoid the error shown in the example above, we need to create appropriate code to handle the exception.
Proper exception handling code should include:
- Try - A function that uses exceptions should be inside the "try" block. If no exception is triggered, the code continues normally. But if an exception is triggered, it is thrown.
- Throw - Specifies how to trigger an exception. Every "throw" must correspond to at least one "catch".
- Catch - The "catch" block catches the exception and creates an object containing the exception information.
Let's trigger an exception:
1 ) { throw new Exception ( " variable value must be less than or equal to 1 " ) ; } return true ; } // trigger exception in try block try { checkNum ( 2 ) ; // if an exception is thrown, the following text will not be output echo ' if this content is output, it means the $number variable ' ; } // catch exception catch ( Exception $e ) { echo ' Message: ' . $e -> getMessage ( ) ; } ?>The code above will produce an error like this:
Message: 变量值必须小于等于 1
Example explanation:
The code above throws an exception and catches it:
- Create the checkNum() function. It checks whether the number is greater than 1. If so, it throws an exception.
- Call the checkNum() function inside the "try" block.
- The exception in the checkNum() function is thrown.
- The "catch" block receives the exception and creates an object ($e) containing the exception information.
- By calling $e->getMessage() on this exception object, the error message from the exception is output.
However, to follow the principle that "every throw must correspond to a catch", you can set up a top-level exception handler to deal with missed errors.
Create a Custom Exception Class
Creating a custom exception handler is very simple. We simply create a dedicated class that can be called when an exception occurs in PHP. This class must be an extension of the exception class.
This custom customException class inherits all the properties of PHP's exception class, and you can add custom functions to it.
Let's start creating the customException class:
getLine ( ) . ' in ' . $this -> getFile ( ) . ' : ' . $this -> getMessage ( ) . ' is not a valid E-Mail address ' ; return $errorMsg ; } } $email = " someone@example...com " ; try { // validate email if ( filter_var ( $email , FILTER_VALIDATE_EMAIL ) === FALSE ) { // if it is an invalid email address, throw an exception throw new customException ( $email ) ; } } catch ( customException $e ) { // display custom message echo $e -> errorMessage ( ) ; } ?>This new class is a copy of the old exception class, plus the errorMessage() function. Because it is a copy of the old class, it inherits the properties and methods from the old class, and we can use the exception class methods such as getLine(), getFile(), and getMessage().
Example explanation:
The code above throws an exception and catches it via a custom exception class:
- The customException() class is created as an extension of the old exception class. This way it inherits all the properties and methods of the old exception class.
- Create the errorMessage() function. If the e-mail address is invalid, the function returns an error message.
- Set the $email variable to an invalid e-mail address string.
- Execute the "try" block; because the e-mail address is invalid, an exception is thrown.
- The "catch" block catches the exception and displays the error message.
Multiple Exceptions
You can use multiple exceptions for a script to detect various situations.
You can use multiple if..else blocks, or a switch block, or nest multiple exceptions. These exceptions can use different exception classes and return different error messages:
getLine ( ) . ' in ' . $this -> getFile ( ) . ' : ' . $this -> getMessage ( ) . ' is not a valid E-Mail address ' ; return $errorMsg ; } } $email = " someone@example.com " ; try { // validate email if ( filter_var ( $email , FILTER_VALIDATE_EMAIL ) === FALSE ) { // if it is an invalid email address, throw an exception throw new customException ( $email ) ; } // check whether "example" is in the email address if ( strpos ( $email , " example " ) !== FALSE ) { throw new Exception ( " $email is an example email " ) ; } } catch ( customException $e ) { echo $e -> errorMessage ( ) ; } catch ( Exception $e ) { echo $e -> getMessage ( ) ; } ?>Example explanation:
The code above tests two conditions, and throws an exception if either condition is not met:
- The customException() class is created as an extension of the old exception class. This way it inherits all the properties and methods of the old exception class.
- Create the errorMessage() function. If the e-mail address is invalid, the function returns an error message.
- Set the $email variable to a string that is a valid e-mail address but contains the string "example".
- Execute the "try" block; under the first condition, no exception is thrown.
- Because the e-mail contains the string "example", the second condition triggers an exception.
- The "catch" block catches the exception and displays the appropriate error message.
If the customException class throws an exception but customException is not caught, and only the base exception is caught, then the exception is handled there.
Re-throwing an Exception
Sometimes, when an exception is thrown, you may want to handle it differently than the standard way. You can re-throw the exception within a "catch" block.
The script should hide system errors from the user. System errors may be important to the programmer, but the user is not interested in them. To make it easier for the user, you can re-throw the exception with a more user-friendly message:
getMessage ( ) . ' is not a valid E-Mail address. ' ; return $errorMsg ; } } $email = " someone@example.com " ; try { try { // check whether "example" is in the email address if ( strpos ( $email , " example " ) !== FALSE ) { // if it is an invalid email address, throw an exception throw new Exception ( $email ) ; } } catch ( Exception $e ) { // re-throw the exception throw new customException ( $email ) ; } } catch ( customException $e ) { // display custom message echo $e -> errorMessage ( ) ; } ?>Example explanation:
The code above checks whether the email address contains the string "example". If it does, it re-throws the exception:
- The customException() class is created as an extension of the old exception class. This way it inherits all the properties and methods of the old exception class.
- Create the errorMessage() function. If the e-mail address is invalid, the function returns an error message.
- Set the $email variable to a string that is a valid e-mail address but contains the string "example".
- The "try" block contains another "try" block, so the exception can be re-thrown.
- Because the e-mail contains the string "example", an exception is triggered.
- The "catch" block catches the exception and re-throws "customException".
- "customException" is caught, and an error message is displayed.
If the exception is not caught in the current "try" block, it will look for a catch block at a higher level.
Setting a Top-Level Exception Handler
The set_exception_handler() function sets a user-defined function to handle all uncaught exceptions.
Exception: " , $exception -> getMessage ( ) ; } set_exception_handler ( ' myException ' ) ; throw new Exception ( ' Uncaught Exception occurred ' ) ; ?>The output of the above code is as follows:
Exception: Uncaught Exception occurred
In the code above, there is no "catch" block; instead, the top-level exception handler is triggered. This function should be used to catch all uncaught exceptions.
Rules for Exceptions
- Code that requires exception handling should be placed inside a try block, so that potential exceptions can be caught.
- Every try or throw block must have at least one corresponding catch block.
- Using multiple catch blocks allows catching different kinds of exceptions.
- An exception can be thrown (re-thrown) in a catch block inside a try block.
In short: if an exception is thrown, it must be caught.