Php Exception
* * *
Exceptions are used to alter the normal flow of a script when a specified error occurs.
* * *
## What is an Exception?
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) occurs. This situation is called an exception.
When an exception is triggered, the following usually happens:
* The current state of the code is saved
* Code execution is switched to a predefined (custom) exception handler function
* Depending on the situation, the handler may restart execution from the saved state, terminate script execution, or continue script execution from another location in the code
We will demonstrate different error handling methods:
* Basic use of exceptions
* Creating a custom exception handler
* Multiple exceptions
* Re-throwing exceptions
* Setting a top-level exception handler
**Note:** Exceptions should only be used for error conditions, not for jumping to another location in the code at a specified point.
* * *
## Basic Use of Exceptions
When an exception is thrown, subsequent code will not be executed; PHP will attempt to find a matching "catch" block.
If an exception is not caught and no corresponding handler is set using set_exception_handler(), a fatal error will occur, outputting an "Uncaught Exception" error message.
Let's try throwing an exception without catching it:
1){throw new Exception("Value must be 1 or below"); }return true; }checkNum(2); ?>
The above code will produce an error similar to this:
Fatal error: Uncaught exception 'Exception' with message 'Value must be 1 or below' in /www//test/test.php:7 Stack trace: #0 /www//test/test.php(13): checkNum(2) #1 {main} thrown in /www//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:
1. Try - Functions that use exceptions should be placed within a "try" block. If no exception is triggered, the code will continue executing normally. However, if an exception is triggered, it will be thrown.
2. Throw - Specifies how to trigger an exception. Each "throw" must correspond to at least one "catch".
3. Catch - The "catch" block catches the exception and creates an object containing exception information.
Let's trigger an exception:
1){throw new Exception("VariableValue must be less than or equal to 1"); }return true; }try{checkNum(2); echo'If this content is output, it indicates that $number Variable'; }catch(Exception$e){echo'Message: ' .$e->getMessage(); }?>
The above code will produce an error similar to this:
Message: VariableValue must be less than or equal to 1
## Example Explanation:
The above code throws and catches an exception:
1. Create the checkNum() function. It checks whether the number is greater than 1. If so, it throws an exception.
2. Call the checkNum() function inside the "try" block.
3. An exception is thrown in the checkNum() function.
4. The "catch" block receives the exception and creates an object ($e) containing exception information.
5. Output the error message from the exception by calling $e->getMessage() on this exception object.
However, to follow the principle "each throw must correspond to a catch", you can set a top-level exception handler to deal with missed errors.
* * *
## Creating a Custom Exception Class
Creating a custom exception handler is very simple. We simply create a specialized class whose functions can be invoked when an exception occurs in PHP. This class must extend the Exception class.
This custom customException class inherits all 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{if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){throw new customException($email); }}catch(customException$e){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 all the properties and methods of the old Exception class, allowing us to use Exception class methods such as getLine(), getFile(), and getMessage().
## Example Explanation:
The above code throws an exception and catches it using a custom exception class:
1. The customException() class is created as an extension of the old Exception class. Thus, it inherits all properties and methods of the old Exception class.
2. Create the errorMessage() function. If the e-mail address is invalid, this function returns an error message.
3. Set the $email variable to an invalid e-mail address string.
4. Execute the "try" block; since the e-mail address is invalid, an exception is thrown.
5. The "catch" block catches the exception and displays the error message.
* * *
## Multiple Exceptions
Multiple exceptions can be used in a script to detect various conditions.
You can use multiple if..else blocks, a switch block, or nested 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{if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){throw new customException($email); }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 above code tests two conditions; if either condition fails, an exception is thrown:
1. The customException() class is created as an extension of the old Exception class. Thus, it inherits all properties and methods of the old Exception class.
2. Create the errorMessage() function. If the e-mail address is invalid, this function returns an error message.
3. Set the $email variable to a string that is a valid e-mail address but contains the string "example".
4. Execute the "try" block; under the first condition, no exception is thrown.
5. Since the e-mail contains the string "example", the second condition triggers an exception.
6. The "catch" block catches the exception and displays the appropriate error message.
If the customException class throws an exception but customException is not caughtβonly the base Exception is caughtβthe exception will be handled there.
* * *
## Re-throwing Exceptions
Sometimes, when an exception is thrown, you may wish to handle it differently than the standard way. You can re-throw an exception inside a "catch" block.
Scripts should hide system errors from users. System errors may be important to developers, but users are not interested in them. To make applications more user-friendly, you can re-throw an exception with a user-friendly message:
getMessage().' is not a valid E-Mail address.'; return$errorMsg; }}$email = "someone@example.com"; try{try{if(strpos($email, "example") !== FALSE){throw new Exception($email); }}catch(Exception$e){throw new customException($email); }}catch(customException$e){echo$e->errorMessage(); }?>
## Example Explanation:
The above code checks whether the email address contains the string "example". If so, it re-throws the exception:
1. The customException() class is created as an extension of the old Exception class. Thus, it inherits all properties and methods of the old Exception class.
2. Create the errorMessage() function. If the e-mail address is invalid, this function returns an error message.
3. Set the $email variable to a string that is a valid e-mail address but contains the string "example".
4. The "try" block contains another "try" block, enabling re-throwing of the exception.
5. Since the e-mail contains the string "example", an exception is triggered.
6. The "catch" block catches the exception and re-throws it as a "customException".
7. The "customException" is caught, and an error message is displayed.
If an 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.
<?php function myException($exception){echo"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 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.
* * *
## Rules for Exceptions
* Code that requires exception handling should be placed inside a try block to catch potential exceptions.
* Each try or throw block must have at least one corresponding catch block.
* Multiple catch blocks can be used to catch different types of exceptions.
* Exceptions can be thrown (re-thrown) inside a catch block within a try block.
In short: If an exception is thrown, it must be caught.
YouTip