Summary of exception handling methods in PHP

Source: Internet
Author: User
Tags error code exception handling getmessage php code throw exception

When an exception is triggered, it usually occurs:

An error exception handling module, similar to other languages, was 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. Use multiple catch to catch exceptions generated by different classes. When a try code 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 within a catch code block. When an exception is thrown, the code that follows (the code block where the exception was 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

Class Notfoundexception extends exception{}
Class Inputexception extends exception{}
Class Dbexception extends exception{}

2, configure the processor does not catch exceptions:

The code is as follows Copy Code
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

The code is as follows Copy Code

Exception_uncaught_handler () function processing:

$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:


if (0!= strcmp ($curAlbum->interest_id, $it))
throw new Notfoundexception (' Sorry, the album you visited doesn't exist ');
The above is the specific usage of PHP custom exception handler


Instance

The code is as follows Copy Code

<?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 code above tests two conditions and throws an exception if any of the conditions are not true:

The 1.customException () class is created as an extension of the old exception class. So it inherits all the properties and methods of the old class.
2. Create the ErrorMessage () function. If the e-mail address is not valid, the function returns an error message.
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. "Catch" Blocks catch exceptions and display the appropriate error messages
If Customexception is not captured, the base exception is tightly captured, where the exception is handled.

Throwing Exceptions again
Sometimes, when an exception is thrown, you may want to handle it in a different way from the standard. You can throw an exception again in a "catch" code block.

The code is as follows Copy Code

<?php
/*
*/
/*
* Summary: The use of the PHP exception is divided into three steps:
* First step: Define the Exception class, if not defined with the system default exception class;
* 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;
* Step fourth: Catch catch catching 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 an exception with catch only
*/
================ Basic Exception class
To create a function that throws an exception
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 ();
}
/*
* Summary: The use of the PHP exception is divided into three steps:
* First step: Define the Exception class, if not defined with the system default exception class;
* 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;
* Step fourth: Catch catch catching 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 an exception with catch only
*/
?>

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.