Summary of php exception handling methods

Source: Internet
Author: User
Tags php exception handling
This article mainly introduces the exception handling methods in php, summarizes common php exception handling techniques in the form of examples, and has some reference value, for more information about how to handle exceptions in php, see the examples in this article. Share it with you for your reference. The specific analysis is as follows:

When an exception is triggered, an error exception handling module similar to other languages is added to PHP5. Exceptions in PHP code can be thrown by throw statements and captured by catch statements. All codes that require exception handling must be placed in the try code block to capture possible exceptions. Each try must have at least one catch corresponding to it.

Multiple catch methods can capture exceptions generated by different classes. when the try code block does not throw an exception or the catch code cannot be found to match the Exception thrown, the PHP code will continue to be executed after the jump to the last catch. Of course, PHP allows a throw exception to be thrown again in the catch code block. When an exception is thrown, it is later (note: refers to the code block where the exception is thrown) and PHP will try to find the first catch that can match it. if an exception is not caught, it is useless to use set_exception_handler () for corresponding processing, PHP will generate a serious error and output the Uncaught Exception... (No exception is captured.

1. the hierarchical relationship of the exception class. the code is as follows:

The code is as follows:

Class NotFoundException extends Exception {}

Class InputException extends Exception {}

Class DBException extends Exception {}

2. configure a processor without capturing exceptions. the code is as follows:

The code is 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. manually throw a DBException exception in the database connection code, but try... Catch to capture and process the exception. The exception will be handled by the PHP custom exception processor, exception_uncaught_handler () function:

The code is 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:

The code is as follows:

If (0! = Strcmp ($ curAlbum-> interest_id, $ it ))

Throw new NotFoundException ('sorry, the album you accessed does not exist ');

The above describes how to use a PHP custom exception processor.

The php instance code is as follows:

The code is as follows:

<? Php
Class customException extends Exception
{
Public function errorMessage ()
{
// Error message
$ ErrorMsg = 'Error on Line'. $ this-> getLine (). 'in'. $ this-> getFile ()
.':'. $ This-> getMessage ().'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 ();
}
?>


The preceding code tests two conditions. if any condition is invalid, an exception is thrown.

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

2. create the errorMessage () function. if the email address is invalid, this function returns an error message.

3. execute the "try" code block. under the first condition, no exception is thrown.

4. because e-mail contains the string "example", the second condition triggers an exception.

5. the "catch" code block captures exceptions and displays appropriate error messages.

If the base mexception is not captured and the base exception is tightly captured, the exception is processed and thrown again. sometimes, when the 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 code is as follows:

Summary: PHP exceptions can be used in three steps:

Step 1: define the exception class. if not defined, use the default exception class;

Step 2: throw an exception when an exception occurs, such as ex1 ($ num2). The exception parameter $ num2 is obtained using the getMessage () of the exception;

Step 3: trigger an exception. use the try clause to throw new ex1 ($ num) when the condition is met );

Step 4: catch (ex2 $ e), equivalent to instantiating a defined exception class ex2 is $ e;

Note: Multiple exceptions can be defined, but only one exception can be triggered. that is to say, only one exception can be caught with catch.

Basic exception class. create a function that throws an exception:

The code is as follows:

Function num ($ num ){
If ($ num> 1) {// exception throw condition
$ Msg = "The value cannot exceed 1"; // error message
Throw new Exception ($ msg); // throw an Exception
}
Echo "value less than 1 ″;
}
// Trigger an exception in the try code block
Try {
Num (3 );
Echo "normal execution ";
}
// Capture exceptions
Catch (Exception $ e ){
Echo "error message:". $ e-> getMessage (); // system method of Exception () to obtain Exception information
Echo "error File:". $ e-> getFile (); // system method of Exception () to obtain the abnormal file name
Echo "number of rows:". $ e-> getLine (); // system method of Exception () to obtain the number of abnormal rows
}
// ================================================ ======================================
Echo"
========================================================== ======================
";
// Extended basic exception class
Function checkEmail ($ email) {// defines a function that can throw an exception to determine the validity of an EMAIL.
If (filter_var ($ email, FILTER_VALIDATE_EMAIL) = false ){
Throw new checkEmailException ($ email); // if an exception is thrown, use EMAIL as the parameter.
}
Echo "the email is valid ";
}
Class checkEmailException extends Exception {// defines an extended Exception class
Public function errormsg (){
$ Msg = "error cause:". $ this-> getMessage (). "It is not a legal EMAIL address! ";
$ Msg. = "error File name:". $ this-> getFile ();
$ Msg. = "error row:". $ this-> getLine ();
Echo $ msg;
}
}
$ Email = "email ..... @ Chhua.com ";
Try {// trigger an exception
CheckEmail ($ email );
}
// Capture exceptions
Catch (checkEmailException $ e ){
$ E-> errormsg ();
}
/// ========================================================= Multiple exceptions capture
Echo"
========================================================== ==============
";
Class ex1 extends Exception {// defines an Exception class
Public function msg (){
$ Msg = "cause of error:". $ this-> getMessage (). "greater than 100
";
$ Msg. = "error File:". $ this-> getFile ()."
";
$ Msg. = "error code:". $ this-> getCode ()."
";
$ Msg. = "number of rows:". $ this-> getLine ()."
";
Echo $ msg;
}
}
Class ex2 extends Exception {// defines an Exception class
Public function msg (){
$ Msg = "error cause:". $ this-> getMessage (). "equal to 100
";
$ Msg. = "error File:". $ this-> getFile ()."
";
$ Msg. = "number of rows:". $ this-> getLine ()."
";
Echo $ msg;
}
}
$ Num2 = 100;
Try {
If ($ num2> 100) {// triggered when the condition is met
Throw new ex1 ($ num2 );
}
If ($ num2 = 100) {// triggered when the condition is met
Throw new ex2 ($ num2 );
}
}
Catch (ex2 $ e) {// catch the exception triggered
$ E-> msg ();
}
Catch (ex1 $ e) {// catch the exception triggered
$ E-> msg ();
}

I hope this article will help you with php programming.

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.