Summary of exception handling methods in PHP _php tips

Source: Internet
Author: User
Tags exception handling getmessage throw exception

The example of this article summarizes the method of exception handling in PHP. Share to everyone for your reference. The specific analysis is as follows:

When an exception is triggered, it usually occurs: An error exception handling module that is similar to other languages is added to the PHP5. The exception generated in the PHP code can be thrown by the throw statement and caught by the catch statement. Code that requires exception handling must be placed inside the try code block to catch possible exceptions. Each try must have at least one catch that corresponds to it.

With multiple catches, you can catch exceptions from different classes, and when a try block no longer throws an exception or cannot find a catch to match the thrown exception, the PHP code continues after the jump to the last catch. Of course, PHP allows you to throw (throw) exceptions again in a catch code block. When an exception is thrown, the code that follows (the code block where the exception is thrown) will not continue, and PHP will try to find the first catch that matches it, if an exception is not captured, And does not use Set_exception_handler () for the corresponding processing, then PHP will produce a serious error, and output uncaught exception ... (Exception not caught) message.

1, the level of the exception class relationship, the code is as follows:

Copy Code code as follows:
Class Notfoundexception extends exception{}

Class Inputexception extends exception{}

Class Dbexception extends exception{}

2, the configuration does not catch the exception of the processor, the code is as follows:

Copy Code code as follows:
function Exception_uncaught_handler (Exception $e) {
Header (' content-type:text/html; Charset=utf-8 ');
if ($e instanceof notfoundexception)
Exit ($e->getmessage ());
ElseIf ($e instanceof dbexception)
Exit ($e->getmessage ());
Else
Exit ($e->getmessage ());
}
Set_exception_handler (' Exception_uncaught_handler ');

3, in the database connection code, manually throw dbexception exception but not using Try...catch for capture processing, the exception will be PHP custom exception handler, Exception_uncaught_handler () function processing:
Copy Code code as follows:
$this->resconn = mysql_connect ($CONFIGS [' Db_host '], $CONFIGS [' Db_user '], $CONFIGS [' db_pwd ']);
if (false = = Is_resource ($this->resconn))
throw new Dbexception (' Database connection failed. '. Mysql_error ($this->resconn));

4, Business logic glance:
Copy Code code as follows:
if (0!= strcmp ($curAlbum->interest_id, $it))

throw new Notfoundexception (' Sorry, the album you visited doesn't exist ');

These are the specific uses of the PHP custom exception handler.

The PHP instance code is as follows:

Copy Code code as follows:
<?php
Class Customexception extends Exception
{
Public Function ErrorMessage ()
{
Error message
$ERRORMSG = ' Error on line '. $this->getline (). $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 a example e-mail");
}
}

catch (Customexception $e)
{
echo $e->errormessage ();
}

catch (Exception $e)
{
echo $e->getmessage ();
}
?>

Example explanation: The above code tests two conditions and throws an exception if any of the conditions are not valid.

The 1.customException () class is created as an extension of the old exception class, so that it inherits all the properties and methods of the old class.

2. Create the ErrorMessage () function, which returns an error message if the e-mail address is not valid.

3. Executes the "Try" code block, which, under the first condition, does not throw an exception.

4. Because e-mail contains the string "Example", the second condition triggers an exception.

5. The "Catch" code block catches the exception and displays the appropriate error message.

If you capture the base exception without capturing the customexception, you handle the exception there, throw the exception back, and sometimes, when the exception is thrown, you might want to handle it in a different way than the standard, and you can do it in a "catch" The code block throws the exception again, as follows:

Summary: The use of the PHP exception is divided into three steps:

Step one: Define the Exception class, and use the system default exception class if not defined;

Step two: When an exception is encountered, throw an exception with throw, such as Ex1 ($num 2), and the parameter of the exception is $num2 with the getmessage () of the exception;

Step three: Trigger the exception, use the TRY clause, throw new Ex1 ($num) when the condition is met;

Fourth step: Catch catches exception catch (Ex2 $e), which is equivalent to instantiating a well-defined exception class ex2 as $e;

Note that exceptions can be defined multiple, but only one can be triggered, that is, you can catch only one exception with catch.

Basic exception class, creating a function that throws an exception:

Copy Code code as follows:
function num ($num) {
if ($num >1) {//exception throw condition
$msg = "value cannot be greater than 1″;//exception hint information
throw new Exception ($msg);//Throw exception
}
echo "Value less than 1 ″;
}
To trigger an exception in a "try" code block
try {
Num (3);
echo "performs normally";
}
Catch exception
catch (Exception $e) {
echo "error message:". $e->getmessage ();//exception () system method gets the exception information
echo "Error file:". $e->getfile (); The system method of//exception () Gets the exception file name
Echo line number:. $e->getline ();//exception () system method gets the number of exception rows
}
//======================================================================
echo "<br>========================================================<br>";
Extend the base exception class
function Checkemail ($email) {//define an exception that can be used to determine the legality of an email
if (Filter_var ($email, Filter_validate_email) ==false) {
throw new Checkemailexception ($email);//Throw exception use email to make parameters
}
echo "Mail Legal";
}
Class Checkemailexception extends exception{//definition Extended Exception class
Public Function errormsg () {
$msg = "Error Reason:". $this->getmessage (). Not a legitimate email address! ";
$msg. = "Error file name:". $this->getfile ();
$msg. = "Error line number:". $this->getline ();
Echo $msg;
}
}
$email = "Email ... @chhua. com";
try {//Trigger exception
Checkemail ($email);
}
Catch exception
catch (Checkemailexception $e) {
$e->errormsg ();
}
================================== Capture of multiple exceptions
echo "<br>===================================================<br>";
Class Ex1 extends exception{//defines an exception class
Public Function msg () {
$msg = "Error Reason:". $this->getmessage (). Greater than 100<br> ";
$msg. = "Error file:". $this->getfile (). <Br> ";
$msg. = "Error code:". $this->getcode (). <br> ";
$msg. = "Number of lines:". $this->getline (). <br> ";
Echo $msg;
}
}
Class Ex2 extends exception{//defines an exception class
Public Function msg () {
$msg = "Error Reason:". $this->getmessage (). equals 100<br> ";
$msg. = "Error file:". $this->getfile (). <Br> ";
$msg. = "Number of lines:". $this->getline (). <br> ";
Echo $msg;
}
}
$num 2=100;
try {
if ($num 2>100) {//trigger when the condition is satisfied
throw new Ex1 ($num 2);
}
if ($num 2==100) {//trigger when the condition is satisfied
throw new Ex2 ($num 2);
}
}
catch (Ex2 $e) {//catch triggered exception
$e->msg ();
}
catch (Ex1 $e) {//catch triggered exception
$e->msg ();
}

I hope this article will help you with your PHP program design.

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.