PHP Exception Handling Methods in code debugging

Source: Internet
Author: User
Tags echo message php exception handling throw exception valid email address

Exception is used to change the normal process of the script when a specified error occurs.


What is an exception?


PHP 5 provides a new object-oriented error handling method.

Exception Handling is used to change the normal process of the script when a specified error (exception) occurs. This is called an exception.

When an exception is triggered, it usually occurs:

The current Code status is saved.
Code execution is switched to a predefined exception processor Function
Depending on the situation, the processor may re-execute the code from the saved code status, terminate the script execution, or continue to execute the script from another position in the code
We will display different error handling methods:

Basic usage of exceptions
Create a custom exception Processor
Multiple exceptions
Throw an exception again.
Set the top-level exception Processor
Basic usage of exceptions
When an exception is thrown, the subsequent code will not be executed, and PHP will try to find the matching "catch" code block.

If the exception is not captured and set_exception_handler () is not used for corresponding processing, a serious (fatal) error will occur ), and output the "Uncaught Exception" (No Exception is caught) error message.

Let's try to throw an exception without capturing it:

<? Php
// Create function with an exceptionfunction
CheckNum ($ number ){
If ($ number> 1 ){
Throw new Exception ("Value must be 1 or below ");
} Return true;
}
// Trigger
ExceptioncheckNum (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 C: webfolderest. php: 6 Stack trace: #0 C: webfolderest. php (12): checkNum (28) #1 {main} thrown in C: webfolderest. php on line 6
Try, throw, and catch
To avoid errors in the above example, we need to create appropriate code to handle exceptions.

The processing process should include:

Try-the abnormal function should be located in the "try" code block. If no exception is triggered, the Code continues as usual. However, if an exception is triggered, an exception is thrown.
Throw-This specifies how to trigger an exception. Each "throw" must correspond to at least one "catch"
The Catch-"catch" code block captures exceptions and creates an object containing exception information.
Let's trigger an exception:

<? Php // create a function that can throw an Exception. function checkNum ($ number) {if ($ number> 1) {throw new Exception ("Value must be 1 or below ");} return true;} // trigger an exception in the "try" code block try {checkNum (2); // If the exception is thrown, this text will not be shown echo If you see this, the number is 1 or below;} // catch an Exception catch (Exception $ e) {echo Message :. $ e-> getMessage () ;}?>
The above code will get an error similar to this:

Message: Value must be 1 or below
Example:
The above code throws an exception and captures it:

Create the checkNum () function. It checks whether the number is greater than 1. If yes, an exception is thrown.
Call the checkNum () function in the "try" code block.
An exception in the checkNum () function is thrown.
The "catch" code block receives the exception and creates an object ($ e) containing the exception information ).
Call $ e-> getMessage () from this exception object to output error messages from this exception.
However, to follow the "each throw must correspond to a catch" principle, you can set a top-level exception processor to handle missed errors.
Create a custom Exception class
It is very easy to create a custom exception handler. We have simply created a special class. When an exception occurs in PHP, we can call its function. This class must be an extension of the exception class.

This custom exception class inherits all attributes of the PHP exception class. You can add custom functions to it.

Let's start to create the exception class:

<? Php
Class customException 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; return $ errorMsg;
}
}
$ Email = "someone @ example...com"; try {
// Check if
If (filter_var ($ email, FILTER_VALIDATE_EMAIL) === FALSE ){
// Throw exception if email is not valid throw
New customException ($ email );
}
} Catch (customException $ e)
{
// Display m message
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 attributes and methods from the old class. We can use methods of the exception class, such as getLine () and getFile () and getMessage ().

Example:
The above code throws an exception and captures it through a custom exception class:

The customException () class is created as an extension of the old exception class. In this way, it inherits all the attributes and methods of the old class.
Create the errorMessage () function. If the email address is invalid, this function returns an error message.
Set the $ email variable to an invalid email address string.
Execute the "try" code block. An exception is thrown because the email address is invalid.
The "catch" code block captures exceptions and displays error messages.
Multiple exceptions
Multiple exceptions can be used for a script to detect multiple cases.

You can use multiple if. else code blocks, a switch code block, or nested 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 on line. $ this-> getLine (). in. $ this-> getFile ().: <B>. $ this-> getMessage (). </B> is not a valid E-Mail address;
Return $ errorMsg;
}
}
$ Email = "someone@example.com"; try {
// Check if
If (filter_var ($ email, FILTER_VALIDATE_EMAIL) === FALSE ){
// Throw exception if email is not valid throw new
CustomException ($ email );
}
// Check for "example" in mail address
If (strpos ($ email, "example ")! = FALSE) {throw new Exception ("$ email is an example e-mail") ;}} catch (customException $ e) {echo $ e-> errorMessage ();} catch (Exception $ e) {echo $ e-> getMessage () ;}?>
Example:
The code above tests two conditions. If any condition is not true, an exception is thrown:

The customException () class is created as an extension of the old exception class. In this way, it inherits all the attributes and methods of the old class.
Create the errorMessage () function. If the email address is invalid, this function returns an error message.
Execute the "try" code block. Under the first condition, no exception is thrown.
Because e-mail contains the string "example", the second condition triggers an exception.
The "catch" code block captures exceptions and displays appropriate error messages.
If the base mexception is not captured and the base exception is captured tightly, the exception is handled there.
Throw an exception again.
Sometimes, when an exception is thrown, you may want to handle it in a different way than the standard. You can throw an exception again in a "catch" code block.

The script should hide system errors from users. For programmers, system errors may be important, but users are not interested in them. To make it easier for users to use, you can throw an exception with user-friendly messages again:

<? Phpclass customException extends Exception {public function errorMessage (){
// Error message
$ ErrorMsg = $ this-> getMessage (). is not a valid E-Mail address.; return $ errorMsg ;}$ email = "someone@example.com"; 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
CustomException ($ email) ;}} catch (customException $ e ){
// Display m message
Echo $ e-> errorMessage () ;}?>
Example:
The code above checks whether the email address contains the string "example ". If yes, an exception is thrown again:

The customException () class is created as an extension of the old exception class. In this way, it inherits all the attributes and methods of the old class.
Create the errorMessage () function. If the email address is invalid, this function returns an error message.
Set the $ email variable to a valid email address, but it contains a string"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.