Table of Contents
Exception Handling with PHP – with examples
Exception Handling with PHP | PHP 5 came up with a replacement object-oriented way of handling errors. After PHP5 we will affect errors easily using the OOP concept. Exception handling is employed to vary the traditional flow of the code execution if a specified error (exceptional) condition occurs. This condition is named 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 things, the handler may then resume the execution from the saved code state, terminate the script execution or continue the script from a special location within the code PHP provides a strong exception handling mechanism that permits you to handle exceptions during a graceful way.
Exception handling is the object-oriented method for handling errors, which provides a more controlled and versatile sort of error reporting. Try, catch, and throw keywords are utilized in exception handling.
Keywords used for Exception Handling with PHP.
Try:
A function using an exception should be during a “try” block. If the exception doesn’t trigger, the code will continue as normal. However, if the exception triggers, the exception is “thrown”.
Throw:
this is often how you trigger an exception. Each “throw” must have a minimum of one “catch”.
Catch:
A “catch” block retrieves an exception and creates an object containing the exception information. When an exception is thrown, code following the statement won’t be executed, and PHP will plan to find the primary matching catch block. I
If an exception isn’t caught, a PHP Fatal Error is going to be issued with an “Uncaught Exception”. An exception is often thrown and caught (“caught”) within PHP. The code could also be surrounded during a try block. Each try must have a minimum of one corresponding catch block. Multiple catch blocks are often wont to catch different classes of exceptions. Exceptions are often thrown (or re-thrown) within a catch block.
Example: Following is the piece of code, copy and paste this code into a file and verify the result.
<?php
try {
$error = ‘Throw this error’;
throw new Exception($error);
// Code following an exception is not executed.
echo ‘Never executed’;
}catch (Exception $e) {
echo ‘Caught exception: ‘, $e->getMessage(), “\n”;
}
// Continue execution
echo ‘Hello World’;
?>
In above example $e->getMessage() function is used to get error message in PHP. There are many functions which can be used from Exception class as following.
- getMessage()− give message of exception
- getCode()− code of exception
- getFile()− source file name
- getLine()− source line
- getTrace()− array of the backtrace()
- getTraceAsString()− formatted string of trace
Creating a Custom Exception for Exception Handling with PHP
We can also create custom exception handler for Exception Handling with PHP. To create such a exception handler we must create a special class with functions that can be called when an exception occurs in PHP. The class must be an extension of the exception class. Custom exception handler class inherits the properties from PHP’s exception class and we can add custom functions in it.
Let’s start with creating an exception class:
<?php
class customExceptionHandler extends Exception {
public function errorMessage() {
//error message
$errorMsg = ‘Error on line ‘.$this->getLine().’ in ‘.$this->getFile()
.’: <b>’.$this->getMessage().'</b> is not a valid E-Mail address, Please use valid one’;
return $errorMsg;
}
}$email = “john@example…com”;
try {
//check if
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
//throw exception if email is not valid.
throw new customExceptionHandler ($email);
}
}catch (customExceptionHandler $e) {
//display custom message
echo $e->errorMessage();
}
?>
Example explained:
The code above throws an exception and catches it with a custom exception class:
- The customExceptionHandler () class is created as an extension of the old exception class. It inherits all methods and properties from the old exception class.
- The errorMessage() function is created. This function returns an error message if an email address is not valid
- The $email variable is set to a string that is not a valid email address.
- The ‘try’ block is executed and an exception is thrown since email address is invalid.
- The ‘catch’ block catches all the exceptions and displays the error message.
Multiple Exceptions
Multiple exceptions is feasible for a script to use multiple exceptions to see for multiple conditions in code. it’s possible to use several if…else blocks, switch, or nest multiple exceptions. These exceptions can use different exception classes and return different error messages.
<?php
class customExceptionHandler extends Exception {
public function errorMessage() {
//error message.
$errorMsg = ‘Error on line ‘.$this->getLine().’ in ‘.$this->getFile()
.’: <b>’.$this->getMessage().'</b> is not valid email address’;
return $errorMsg;
}
}$email = “[email protected]”;
try {
//check if
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
//throw exception if e-mail is not valid
throw new customExceptionHandler($email);
}
//check for “example” in email
if(strpos($email, “example”) !== FALSE) {
throw new Exception(“$email is an example e-mail”);
}
}catch (customExceptionHandler $e) {
echo $e->errorMessage();
}catch(Exception $e) {
echo $e->getMessage();
}
?>
Example explained:
The code above tests two conditions and throws an exception if any of the conditions are not met:
- The customExceptionHandler() class is created as an extension of the old exception class. This way it inherits all methods and properties from the old exception class
- The errorMessage() function is created. This function returns an error message if an e-mail address is invalid
- The $email variable is set to a string that is a valid email address, but contains the string “example”
- The ‘try’ block is executed and an exception is not thrown on the first condition
- The second condition triggers an exception since the e-mail contains the string “example”
- The ‘catch’ block catches the exceptions and display us the correct error messages.
If the exception thrown were of the class customExceptionHandler and there were no customExceptionHandler catch, only the base exception catch, the exception would be handled there.
Re-throwing Exceptions
Sometimes, when an exception is thrown, you’ll wish to handle it differently than the quality way. it’s possible to throw an exception a second time within a “catch” block.
A script should hide system errors from users. System errors could also be important for the coder, but are of no interest to the user. to form things easier for the user you’ll re-throw the exception with a user friendly message:
<?php
class customExceptionHandler extends Exception {
public function errorMessage() {
//error message
$errorMsg = $this->getMessage().’ is not a valid E-Mail address.’;
return $errorMsg;
}
}$email = “[email protected]”;
try {
try {
//check for “example” in mail address
if(strpos($email, “example”) !== FALSE) {
//throw exception if email is not valid
throw new Exception($email);
}
}
catch(Exception $e) {
//re-throw exception
throw new customExceptionHandler($email);
}
}catch (customExceptionHandler $e) {
//display custom message
echo $e->errorMessage();
}
?>
Example explained:
The code above tests if the email address contains the string “example” in it, if it does, the exception is rethrown:
- The customExceptionHandler() class is created as an extension of the old exception class. This way it inherits all methods and properties from the old exception class
- The errorMessage() function is created. This function returns an error message if an email address is invalid
- The $email variable is set to a string that is a valid email address, but contains the string “example”
- The “try” block contains another “try” block to make it possible to re-throw the exception
- The exception is triggered since the email contains the string “example”
- The “catch” block catches the exception and re-throws a “customExceptionHandler”
- The “customExceptionHandler” is caught and displays an error message
If the exception is not caught in its current “try” block, it will search for a catch block on “higher levels”.
Exception Handling with PHP
Rules for exceptions
- Code could also be surrounded during a try block, to assist catch potential exceptions.
- Each try block or “throw” must have a minimum of one corresponding catch block.
- Multiple catch blocks are often wont to catch different classes of exceptions.
- Exceptions are often thrown (or re-thrown) during a catch block within a try block.