Home >Backend Development >PHP Tutorial >Detailed explanation of PHP exception handling_PHP tutorial
Exception handling (also known as error handling) function provides methods to handle errors or abnormal conditions that occur when the program is running.
Exception handling is usually a measure taken to prevent unknown errors from occurring. The advantage of exception handling is that you no longer have to rack your brains to consider various errors. This provides a very effective method for handling certain types of errors, greatly improving programming efficiency. When an exception is triggered, it usually happens:
The current code status is saved
Code execution is switched to the predefined 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
PHP 5 provides a new object-oriented error handling method. You can use try, throw, and catch exceptions. That is, use try to detect whether an exception is thrown. If an exception is thrown, use catch to catch the exception.
A try must have at least one corresponding catch. Define multiple catches to capture different objects. PHP will execute these catches in the order they are defined until the last one is completed. Within these catches, new exceptions can be thrown.
1. Abnormal use
When an exception is thrown, the following code will not continue to execute, and PHP will try to find a matching "catch" code block. If an exception is not caught, and set_exception_handler() is not used for corresponding processing, then PHP will generate a serious error and output a prompt message of Uncaught Exception...).
Throw an exception without catching it:
ini_set('display_errors', 'On');
error_reporting(E_ALL & ~ E_WARNING);
$error = 'Always throw this error';
throw new Exception($error);
// Continue execution
echo 'Hello World';
?>
The above code will get a fatal error like this:
Fatal error: Uncaught exception 'Exception' with message 'Always throw this error' in E:sngrepindex.php on line 5
Exception: Always throw this error in E:sngrepindex.php on line 5
Call Stack:
0.0005 330680 1. {main}() E:sngrepindex.php:0
2. Try, throw and catch
To avoid the above fatal error, you can use try catch to catch it.
The handler 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 - This specifies how to trigger the exception. Each "throw" must correspond to at least one "catch"
Catch - The "catch" code block will catch the exception and create an object containing the exception information
Throw an exception and catch it, you can continue to execute the following code:
try {
$error = 'Always throw this error';
Throw new Exception($error);
// From here on, the code within the tra code block will not be executed
echo 'Never executed';
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(),'
';
}
// Continue execution
echo 'Hello World';
?>
In the "try" code block, check whether a "throw" exception is thrown, and an exception is thrown here.
The "catch" code block receives the exception and creates an object ($e) containing the exception information.
By calling $e->getMessage() from this exception object, output the error message from the exception
In order to follow the principle of "each throw must correspond to a catch", you can set up a top-level exception handler to handle missed errors.
3. Extend PHP’s built-in exception handling class
Users can extend PHP’s built-in exception handling classes with custom exception handling classes. The following code illustrates which properties and methods in the built-in exception handling class are accessible and inheritable in subclasses. (Note: The following code is only to illustrate the structure of the built-in exception handling class. It is not a usable code with practical significance.)
class Exception
{
Protected $message = 'Unknown exception'; // Exception message
protected $code = 0; //User-defined exception code
protected $file; // The file name where the exception occurred
protected $line;
Function __construct($message = null, $code = 0);
final function getMessage(); // Return exception message
final function getCode(); // Return exception code
final function getFile(); // Return the file name where the exception occurred
final function getLine(); // Return the code line number where the exception occurred
final function getTrace(); // backtrace() array www.2cto.com
final function getTraceAsString(); // getTrace() information that has been formatted into a string
/* Overloadable methods */
function __toString(); // Outputable string
}
If you use a custom class to extend the built-in exception handling class and redefine the constructor, it is recommended to call parent::__construct() at the same time to check whether all variables have been assigned values. When the object wants to output a string, you can overload __toString() and customize the output style.
/**
*
* Customize an exception handling class
*/
class MyException extends Exception
{
// Redefine the constructor so that message becomes a property that must be specified
Public function __construct($message, $code = 0) {
// Customized code
// Make sure all variables are assigned correctly
parent::__construct($message, $code);
}
// Customize the style of string output */
Public function __toString() {
Return __CLASS__ . ": [{$this->code}]: {$this->message}n";
}
Public function customFunction() {
echo "A Custom function for this type of exceptionn";
}
}
// Example 1: Throw a custom exception, but there is no default exception
echo 'Example 1', '
';
try {
// Throw a custom exception
Throw new MyException('1 is an invalid parameter', 5);
} catch (MyException $e) { // Catch exception
echo "Caught my exceptionn", $e;
$e->customFunction();
} catch (Exception $e) { // Ignored
echo "Caught Default Exceptionn", $e;
}
// Execute subsequent code
// Example 2: Throw the default exception but no custom exception
echo '
', ' Example 2:', '
';
try {
// Throw the default exception
Throw new Exception('2 isnt allowed as a parameter', 6);
} catch (MyException $e) { // Cannot match the exception type and is ignored
echo "Caught my exceptionn", $e;
$e->customFunction();
} catch (Exception $e) {// Catch exception
echo "Caught Default Exceptionn", $e;
}
// Execute subsequent code
// Example 3: Throw a custom exception and use the default exception class object to capture
echo '
', ' Example 3:', '
';
try {
// Throw a custom exception
Throw new MyException('3 isnt allowed as a parameter', 6);
} catch (Exception $e) { // Catch exception
echo "Default Exception caughtn", $e;
}
// Execute subsequent code
// Example 4
echo '
', ' Example 4:', '
';
try {
echo 'No Exception ';
} catch (Exception $e) { // No exception, ignored
echo "Default Exception caughtn", $e;
}
// Execute subsequent code
The MyException class was created as an extension of the old exception class. This way it inherits all the properties and methods of the old class, and we can use the methods of the exception class, such as getLine(), getFile() and getMessage().
4. Nested exception handling
If the exception is not caught in the inner "try" code block, it will look for the catch code block on the outer level to catch it.
try {
Try {
Throw new MyException('foo!');
} catch (MyException $e) {
/* rethrow it */
$e->customFunction();
throw $e;
}
} catch (Exception $e) {
var_dump($e->getMessage());
}
5. Set Top Level Exception Handler
The set_exception_handler() function can set a user-defined function that handles all uncaught exceptions.
function myException($exception)
{
echo "Exception: " , $exception->getMessage();
}
set_exception_handler('myException');
throw new Exception('Uncaught Exception occurred');
Output result:
Exception: Uncaught Exception occurred
6. Abnormal rules
Code that requires exception handling should be placed within a try block to catch potential exceptions.
Every 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 re-thrown in a catch block within a try block.
In short: if an exception is thrown, you must catch it, otherwise the program terminates execution.
Excerpted from Programming Life, guisu column