PHP Exception Handling

Source: Internet
Author: User
Tags php exception handling

What is an exception?
PHP 5 provides a new approach to object-oriented error handling.
Exception handling is used to change the normal process of a script when a specified error (exception) condition occurs. This condition is called an exception.
When an exception is triggered, it usually occurs:
Current code state is saved
Code execution is switched to pre-defined (custom) exception handler functions
Depending on the situation, the processor may start executing the code again from the saved code state, terminating the script execution, or continuing the script from another location in the code
We will show you different error handling methods:
Basic use of exceptions
Creating a custom exception handler
Multiple exceptions
To re-throw an exception
Setting the top-level exception handler
Note: Exceptions should be used only in the wrong situation, and should not be used to jump to another location in the code at a specified point.
Basic use of exceptions
When the exception is thrown, the subsequent code does not continue, and PHP tries to find a matching "catch" block.
If the exception is not captured and does not use Set_exception_handler () for appropriate processing, a serious error (fatal error) will occur, and an error message "Uncaught exception" (uncaught exception) is output.
Let's try to throw an exception without catching it:
<?php
Create a function with exception handling
function Checknum ($number)
{
if ($number >1)
{
throw new Exception ("Value must be 1 or below");
}
return true;
}

Triggering an exception
Checknum (2);
?>
The above code will get an error like this:
Fatal error:uncaught Exception ' exception ' with message ' Value must is 1 or below ' In/www/runoob/test/test.php:7 Stack t Race: #0/www/runoob/test/test.php: Checknum (2) #1 {main} thrown in/www/runoob/test/test.php on line 7
Try, throw, and catch
To avoid errors in the above example, we need to create the appropriate code to handle the exception.
Proper handling of exception codes should include:
Try-the function that uses the exception should be in the "try" code block. If no exception is triggered, the code will continue to execute as usual. However, if an exception is triggered, an exception is thrown.
Throw-Specifies how to trigger an exception. Each "throw" must correspond to at least one "catch".
Catch-The catch code block catches the exception and creates an object that contains the exception information.
Let's trigger an exception:
<?php
Create a function with exception handling
function Checknum ($number)
{
if ($number >1)
{
throw new Exception ("Variable value must be less than or equal to 1");
}
return true;
}

Triggering an exception in a try block
Try
{
Checknum (2);
If an exception is thrown, the following text is not output
Echo ' If output this content, description $number variable ';
}
Catching exceptions
catch (Exception $e)
{
Echo ' Message: '. $e->getmessage ();
}
?>
The above code will get an error like this:
Message: Variable value must be less than or equal to 1
Example Explanation:
The above code throws an exception and captures it:
Create the Checknum () function. It detects if the number is greater than 1. If it is, an exception is thrown.
Call the Checknum () function in the "Try" code block.
The exception in the Checknum () function is thrown.
The catch code block receives the exception and creates an object ($e) that contains the exception information.
The error message from this exception is output by calling $e->getmessage () from this exception object.
However, to follow the principle that each throw must correspond to a catch, you can set up a top-level exception handler to handle the missing error.
To create a custom Exception class
Creating a custom exception handler is straightforward. We have simply created a special class that can call its function when an exception occurs in PHP. The class must be an extension of the exception class.
This custom customexception class inherits all the properties of the PHP exception class, and you can add custom functions to it.
We started to create the Customexception class:
<?php
Class Customexception extends Exception
{
Public Function ErrorMessage ()
{
Error message
$ERRORMSG = ' ERROR line number '. $this->getline (). ' In '. $this->getfile ()
. ': <b> '. $this->getmessage (). ' </b> is not a valid e-mail address ';
return $ERRORMSG;
}
}

$email = "[email protected]";

Try
{
//Detect Mailbox
if (Filter_var ($email, filter_validate_email) = = = FALSE)
{
//If it is an illegal e-mail address, throw an exception
throw new Customexception ($email);
}
}

catch (Customexception $e)
{
Display custom 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 properties and methods from the old class, and we can use the methods of the exception class, such as GetLine (), GetFile (), and GetMessage ().
Example Explanation:
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 properties and methods of the old exception class.
Create the ErrorMessage () function. If the e-mail address is not valid, the function returns an error message.
Set the $email variable to an illegal e-mail address string.
Executes a "try" block of code that throws an exception because the e-mail address is not valid.
The catch code block catches the exception and displays an error message.
Multiple exceptions
You can use multiple exceptions for a script to detect multiple situations.
You can use multiple if: else code block, or a switch code block, or nested multiple 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 line number '. $this->getline (). ' In '. $this->getfile ()
. ': <b> '. $this->getmessage (). ' </b> is not a valid e-mail address ';
return $ERRORMSG;
}
}

$email = "[email protected]";

Try
{
Check mailbox
if (Filter_var ($email, filter_validate_email) = = = FALSE)
{
If it is an illegal e-mail address, throw an exception
throw new Customexception ($email);
}
Detects if "Example" is in the e-mail address
if (Strpos ($email, "example")!== FALSE)
{
throw new Exception ("$email is example mailbox");
}
}
catch (Customexception $e)
{
echo $e->errormessage ();
}
catch (Exception $e)
{
echo $e-bjrongjinhuiyin.com>getmessage ();
}
?>
Example Explanation:
The code above melts Kim tests two conditions and throws an exception if either of these conditions is not true:
The Customexception () class is created as an extension of the old exception class. In this way it inherits all the properties and methods of the old exception class.
Create the ErrorMessage () function. If the e-mail address is not valid, the function returns an error message.
Set the $email variable to a string that is a valid e-mail address, but contains the string "example".
Executes a "try" block of code that, under the first condition, does not throw an exception.
Because e-mail contains the string "Example", the second condition triggers an exception.
The catch code block catches the exception and displays the appropriate error message.
If the Customexception class throws an exception but does not capture customexception, only the base exception is captured, then the exception is handled there.
To re-throw an exception
Sometimes, when an exception is thrown, you might want to handle it in a different way from the standard. You can throw an exception again in a "catch" code block.
The script should hide the system error from the user. For programmers, system errors may be important, but users are not interested in them. To make it easier for users to use, you can again throw an exception with a friendly message to the user:
<?php
Class Customexception extends Exception
{
Public Function ErrorMessage ()
{
Error message
$ERRORMSG = $this->getmessage (). ' is not a valid e-mail address. ‘;
return $ERRORMSG;
}
}

$email = "[email protected]";

Try
{
Try
{
Detects if "Example" is in the e-mail address
if (Strpos ($email, "example")!== FALSE)
{
If it is an illegal e-mail address, throw an exception
throw new Exception ($email);
}
}
catch (Exception $e)
{
To re-throw an exception
throw new Customexception ($email);
}
}
catch (Customexception $e)
{
Display custom Information
echo $e->errormessage ();
}
?>
Example Explanation:
The above code detects if the message address contains the string "example". If there is, throw the exception again:
The Customexception () class is created as an extension of the old exception class. In this way it inherits all the properties and methods of the old exception class.
Create the ErrorMessage () function. If the e-mail address is not valid, the function returns an error message.
Set the $email variable to a string that is a valid e-mail address, but contains the string "example".
The "Try" code block contains another "try" code block so that you can throw the exception again.
The exception is triggered because e-mail contains the string "example".
The catch block captures the exception and re-throws "Customexception".
"Customexception" is captured and an error message is displayed.
If the exception is not caught in the current "try" code block, it looks for a catch code block at a higher level.

PHP Exception Handling

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.