Exceptions are used to alter the normal flow of a script when a specified error occurs.
PHP 5 provides a new object-oriented approach to error handling.
Exception handling is used to alter the normal flow of a script when a specified error (exception) condition occurs. This situation is called an exception.
When an exception is triggered, it usually happens:
The current code state is saved
Code execution is switched to a predefined (custom) exception handler function
Depending on the situation, the processor may restart code execution from a saved code state, terminate script execution, or continue script execution from another location in the code.
We will show different error handling methods:
Basic usage of exceptions
Create a custom exception handler
Multiple exceptions
rethrow exception
Set top-level exception handler
Note: Exceptions should only be used in error situations and should not be used to jump to another location in the code at a specified point.
When an exception is thrown, the following code will not continue to execute, and PHP will try to find a matching "catch" block of code.
If the exception is not caught and is not handled accordingly using set_exception_handler(), a serious error (fatal error) will occur and an "Uncaught Exception" error message will be output.
Let's try throwing an exception without catching it:
<?php // Create a function with exception handling function checkNum ( $number ) { if ( $number > 1 ) { throw new Exception ( " Value must be 1 or below " ) ; } return true ; } // trigger exception checkNum ( 2 ) ; ?>
The above code will get an error similar to this:
Fatal error: Uncaught exception 'Exception' with message 'Value must be 1 or below' in /www/codercto/test/test.php:7 Stack trace: #0 /www/codercto/test/test.php(13): checkNum(2) #1 {main} thrown in /www/codercto/test/test.php on line 7
To avoid the error seen in the above example, we need to create appropriate code to handle exceptions.
Appropriate exception handling code should include:
Try - Functions that use exceptions should be inside a "try" block. If no exception is triggered, the code continues execution as usual. But if an exception is triggered, an exception will be thrown.
Throw - specifies how to trigger the exception. Each "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:
<?php // Create a function with exception handling function checkNum ( $number ) { if ( $number > 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, explain the $number variable ' ; } // catch exception catch ( Exception $e ) { echo ' Message: ' . $e -> getMessage ( ) ; } ?>
The above code will get an error similar to this:
Message: Variable value must be less than or equal to 1
The above code throws an exception and catches it:
Create checkNum() function. It detects whether the number is greater than 1. If so, throw an exception.
Call the checkNum() function in the "try" block.
Exception in checkNum() function is thrown.
The "catch" code block receives the exception and creates an object ($e) containing the exception information.
Output the error message from this exception by calling $e->getMessage() from this exception object.
However, in order to follow the "every throw must correspond to a catch" principle, you can set up a top-level exception handler to handle missed errors.
Creating custom exception handlers is very simple. We simply created a specialized class whose functions 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.
We start by creating the customException class:
<?php class customException extends Exception { public function errorMessage ( ) { // error message $errorMsg = ' Error line number ' . $this -> getLine ( ) . ' in ' . $this -> getFile ( ) . ' : <b> ' . $this -> getMessage ( ) . ' </b> No A valid E-Mail address ' ; return $errorMsg ; } } $email = " [email protected] " ; try { // Detect email if ( filter_var ( $email , FILTER_VALIDATE_EMAIL ) === FALSE ) { // If it is an illegal 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. Just because it is a copy of the old class, it inherits properties and methods from the old class, and we can use the methods of the exception class, such as getLine(), getFile(), and getMessage().
The above code throws an exception and catches it through a custom exception class:
The customException() class was created as an extension of the old exception class. This way it inherits all the properties and methods of the old exception class.
Create errorMessage() function. If the e-mail address is not valid, this function returns an error message.
Set the $email variable to an illegal e-mail address string.
The "try" code block is executed and an exception is thrown because the e-mail address is invalid.
The "catch" code block catches the exception and displays an error message.
You can use multiple exceptions for a script to detect multiple situations.
You can use multiple if..else code blocks, or a switch code block, or nest multiple exceptions. These exceptions can use different exception classes and return different error messages:
<?php class customException extends Exception { public function errorMessage ( ) { // error message $errorMsg = ' Error line number ' . $this -> getLine ( ) . ' in ' . $this -> getFile ( ) . ' : <b> ' . $this -> getMessage ( ) . ' </b> No A valid E-Mail address ' ; return $errorMsg ; } } $email = " [email protected] " ; try { // Detect email if ( filter_var ( $email , FILTER_VALIDATE_EMAIL ) === FALSE ) { // If it is an illegal 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 the example mailbox " ) ; } } catch ( customException $e ) { echo $e -> errorMessage ( ) ; } catch ( Exception $e ) { echo $e -> getMessage ( ) ; } ?>
The above code tests two conditions and throws an exception if either condition is not true:
The customException() class was created as an extension of the old exception class. This way it inherits all the properties and methods of the old exception class.
Create errorMessage() function. If the e-mail address is not valid, this 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 of code, and in the first condition, no exception will be thrown.
Since the e-mail contains the string "example", the second condition will trigger an exception.
The "catch" block catches the exception and displays an appropriate error message.
If the customException class throws an exception, but the customException is not caught, only the base exception is caught, the exception is handled there.
Sometimes, when an exception is thrown, you may want to handle it differently than the standard. The exception can be thrown again in a "catch" block.
The script should hide system errors from the user. System errors may be important to programmers, but users are not interested in them. To make it easier for users, you can throw the exception again with a user-friendly message:
<?php class customException extends Exception { public function errorMessage ( ) { // error message $errorMsg = $this -> getMessage ( ) . ' Not a valid E-Mail address. ' ; return $errorMsg ; } } $email = " [email protected] " ; try { try { // Check whether "example" is in the email address if ( strpos ( $email , " example " ) !== FALSE ) { // If it is an illegal email address, throw an exception throw new Exception ( $email ) ; } } catch ( Exception $e ) { // Rethrow the exception throw new customException ( $email ) ; } } catch ( customException $e ) { // Display custom information echo $e -> errorMessage ( ) ; } ?>
The above code detects whether the string "example" is contained in the email address. If so, throw the exception again:
The customException() class was created as an extension of the old exception class. This way it inherits all the properties and methods of the old exception class.
Create errorMessage() function. If the e-mail address is not valid, this function returns an error message.
Set the $email variable to a string that is a valid e-mail address but contains the string "example".
A "try" block contains another "try" block so that the exception can be thrown again.
Because the e-mail contains the string "example", the exception is triggered.
The "catch" code block catches the exception and rethrows "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.
The set_exception_handler() function sets a user-defined function that handles all uncaught exceptions.
<?php function myException ( $exception ) { echo " <b>Exception:</b> " , $exception -> getMessage ( ) ; } set_exception_handler ( ' myException ' ) ; throw new Exception ( ' Uncaught Exception occurred ' ) ; ?>
The output of the above code looks like this:
Exception: Uncaught Exception occurred
In the above code, there is no "catch" block, instead the top-level exception handler is triggered. This function should be used to catch all uncaught exceptions.
Code that requires exception handling should be placed within a try block to catch potential exceptions.
Each try or throw block must have at least one corresponding catch block.
Use multiple catch blocks to catch different kinds of exceptions.
Exceptions can be thrown (rethrown) in a catch block within a try block.
In short: if an exception is thrown, you must catch it.