English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, you will learn how to raise and catch exceptions in PHP.
exceptions are signals indicating that some kind of exceptional event or error has occurred. Exceptions can occur for many reasons, such as, database connection or query failure, the file you are trying to access does not exist, etc.
PHP provides a powerful exception handling mechanism that allows you to handle exceptions in an elegant way. Unlike PHP's traditionalerror handlingsystem, in contrast, exception handling is a method used for errororientedThe method, which provides a more specific and flexible error reporting form. The exception model was first introduced in PHP 5introduced.
In the exception-based method, the program code is written in the try block. When an exception event occurs during the execution of the code in the try block, an exception can be raised using the throw statement. It is then caught and parsed by one or more catch blocks.
The following example demonstrates how exception handling works:
<?php function division($dividend, $divisor) { //If the divisor is zero, an exception will be thrown if($divisor == 0) { throw new Exception('Division by zero.'); } else { $quotient = $dividend / $divisor; echo "<p>$dividend / $divisor = $quotient</p>"; } } try{ division(10, 2); division(30, -4); division(15, 0); //If an exception is thrown, the following lines will not be executed echo '<p>All operations executed successfully.</p>'; } catch(Exception $e){ //Handle exception echo "<p>Caught exception: " . $e->getMessage() . "</p>"; } // Continue execution echo "<p>Hello World!/p>"; ?>
You may wonder what this code is about. Well, let's go through each part of this code one by one to better understand.
There are four basic parts in PHP's exception handling system: try, throw, catch, and Exception class. The following list describes how each part works.
The division() function in the example checks if the divisor is equal to zero. If so, it throws an exception using PHP's throw statement. Otherwise, this function performs division with the given numbers and displays the result.
Then, in the try block, the division() function is called with different parameters. If an exception is generated while executing the code in the try block, PHP will stop executing at that point and try to find the corresponding catch block. If found, the code in the catch block is executed; otherwise, a fatal error is generated.
The catch block usually catches exceptions thrown in the try block and creates an object (e) containing exception information. You can retrieve the error message from this object using the getMessage() method of the exception.
PHP's Exception class also provides methods such as getCode(), getFile(), getLine(), and getTraceAsString() to generate detailed debugging information.
<?php //Disable default error reporting error_reporting(0); try{ $file = "somefile.txt"; //Attempt to open file $handle = fopen($file, "r"); if(!$handle){ throw new Exception("Unable to open file!", 5); } //Attempt to read file content $content = fread($handle, filesize($file)); if(!$content){ throw new Exception("Could not read file!", 10); } //Close file handle fclose($handle); //Display file content echo $content; } catch(Exception $e){ echo "<h3>Caught Exception!/h3>"; echo "<p>Error message: " . $e->getMessage() . "</p>"; echo "<p>File: " . $e->getFile() . "</p>"; echo "<p>Line: " . $e->getLine() . "</p>"; echo "<p>Error code: " . $e->getCode() . "</p>"; echo "<p>Trace: " . $e->getTraceAsString() . "</p>"; } ?>
The constructor of the exception can optionally accept an exception message and an exception code. Although the exception message is usually used to display general information about the cause of the error, the exception code can be used to classify errors. The provided exception code can later be retrieved through the getCode() method of Exception.
Tip:Exceptions should only be used for special cases; they should not be used to specify the normal application flow, such as jumping to another location in the script. This can adversely affect the performance of the application.
You can even define your own custom exception handlers to handle different types of exceptions in different ways. It allows you to use separate catch blocks for each type of exception.
You can define your custom exceptions by extending the Exception class, as Exception is the base class for all exceptions. Custom exception classes inherit all properties and methods of the PHP Exception class. You can also add custom methods to the custom exception class. Let's look at the following example:
<?php //Extending the Exception class class EmptyEmailException extends Exception {} class InvalidEmailException extends Exception {} $email = "[email protected]"; try{ //If the email is empty, throw an exception if($email == ""){ throw new EmptyEmailException("<p>Please enter your email address!</p>"); } //If the email is invalid, throw an exception if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) { throw new InvalidEmailException("<p><b>$email</b> Not a valid email address!/p>"); } // If the email is valid, display a success message echo "<p>Success: Email verification successful.</p>"; catch(EmptyEmailException $e){ echo $e->getMessage(); catch(InvalidEmailException $e){ echo $e->getMessage(); } ?>
In the above example, we derived two new exception classes from the Exception base class:EmptyEmailExceptionandInvalidEmailException. Multiple catch blocks are used to display different error messages depending on the generated exception type.
Since these custom exception classes inherit properties and methods from the Exception class, we can use exception class methods such as getMessage(), getLine(), getFile(), etc. to retrieve error information from the exception object.
As discussed earlier in this chapter, if an exception is not caught, PHP will generate a fatal error with a message like "Uncaught Exception ...". This error message may contain sensitive information, such as the name of the file where the problem occurred and the line number. If you do not want to expose such information to the user, you can create a custom function and register it with set_exception_handler() to handle all uncaught exceptions.
<?php function handleUncaughtException($e){ //Display general error message to the user echo "Oops! Something went wrong. Please try again, if the problem persists, please contact us."; // Construct error string $error = "Uncaught Exception: " . $message = date("Y-m-d H:i:s - "); $error .= $e->getMessage() . " in file " . $e->getFile() . " on line " . $e->getLine() . "\n"; //Record detailed error information in the file error_log($error, 3, "var/log/exceptionLog.log"); } //Register a custom exception handler set_exception_handler("handleUncaughtException"); // Throw exception throw new Exception("Testing Exception!"); ?>
Note:Uncaught exceptions always lead to script termination. Therefore, if you want the script to continue executing after an exception occurs, each try block must have at least one corresponding catch block.