Usage of Exception handling classes in PHP

Source: Internet
Author: User
Tags error handling exception handling getmessage
The code is as follows: Copy code
<? Php
Try {
$ A = 10/0;
} Catch (Exception $ e ){
Echo "throw an exception ";
    }
?>

The above code does not output "throw an exception", but outputs the error message: Warning: Division by zero in ......

Note: The try block does not throw an exception, but is handled according to the default error handling mechanism of the system.

So whether an exception can be caught depends on whether an exception is thrown.

 

The code is as follows: Copy code

<? Php
Class Exception
{
Protected $ message = 'unknown exception'; // exception information
Protected $ code = 0; // custom exception code
Protected $ file; // file name with an exception
Protected $ line; // The code line number with an exception

Function _ construct ($ message = null, $ code = 0 );

Final function getMessage (); // returns exception information
Final function getCode (); // returns the exception code
Final function getFile (); // returns the file name with an exception
Final function getLine (); // return the code line number in which an exception occurs.
Final function getTrace (); // backtrace () array
Final function getTraceAsString (); // getTrace () information formatted as a string

/* Methods that can be reloaded */
Function _ toString (); // output string
}
?>

Simple usage: (throws an error message through an exception)

The code is as follows: Copy code

Try {
$ Error = 'My error! ';
Throw new Exception ($ error)
} Catch (Exception $ e ){
Echo $ e-> getMessage ();
}

We can extend this class for our convenience.

 

The code is as follows: Copy code

Class MyException extends Exception
{
// Redefine the constructor to make the message a required attribute
Public function _ construct ($ message, $ code = 0 ){
// Custom code

// Make sure all variables are correctly assigned values
Parent: :__ construct ($ message, $ code );
    }

// Customize the output style of the string
Public function _ toString (){
Return _ CLASS _. ": [{$ this-> code}]: {$ this-> message} n ";
    }

Public function customFunction (){
Echo "A Custom function for this type of exceptionn ";
    }
}

The basic idea of exception handling is that the code is called and executed in try code. If an error occurs in the try block, we can execute a process that throws an exception. Some programming languages, such as java, will automatically throw exceptions under certain circumstances. In php, an exception must be thrown manually. You can throw an exception as follows:

The code is as follows: Copy code

Throw new Exception ('message', code );

The Throw keyword triggers the exception handling mechanism. It is a language structure, not a function, but must pass a value to it. It requires an acceptance object. In the simplest case, you can instantiate a built-in Exception class.

Finally, after the try code, at least one catch code block must be provided. Multiple catch code blocks can be associated with a try code block. If each catch code block can capture a different type of exception, it makes sense to use multiple catch code blocks. For example, if you want to catch exceptions of the Exception class, the code is as follows:

 

The code is as follows: Copy code

Catch (Exception $ e)

{

// Handing exception

}

The object captured by the Catch code is the object that causes an exception and is passed to the throw statement (thrown by the throw statement ). Exception class instances are a good choice.

The Exception class provides the following built-in methods:

Getcode ()-return the code passed to the constructor.

GetMessage ()-return the message passed to the constructor.

GetFile ()-return the path of the file that generates the exception code

GetLine ()-return the row of the code that generates an exception.
Note:

When an exception is caught, the subsequent code in the try () block will not continue to be executed, but will try to find the matched "catch" block.
When an exception is thrown, if no catch processing is performed, the "Uncaught Exception 'exception' error will be reported.

The code is as follows: Copy code
<? Php
Function test ($ val ){
'If ($ val> 100 ){
Throw new Exception ("prompt message: Your input value is too large ");
        }
    }
Test (111 );
?>

3. When an exception is thrown, the catch statement block can be processed or not processed.

The following are some codes of the user registration function.

Try {
// Check forms filled in
If (! Filled_out ($ _ POST )){
Throw new Exception ('You have not entered the form, please enter it ');
     }
// Check email address not valid
If (! Check_email ($ email )){
Throw new Exception ('invalid email format ');
     }
// Check whether the density length is greater than 6
If (strlen ($ passwd <6 )){
Throw new Exception ('density length should be greater than 6 ');
     }
// Check whether the two passwords are equal
If ($ passwd! = $ Passwd1 ){
Throw new Exception ('Two passwords are different. Please input them again ');
     }
// Check whether the length of the user name is correct
If (strlen ($ username)> 16 ){
Throw new Exception ('The user name length does not match, please input it again ');
     }
  
} Catch (Exception $ e ){
Echo $ e-> getMessage (); // output exception information.
 }

 

Php handles exceptions like java. It uses try {} catch (){}

Which of the following functions is used to define a top-level exception processor?
Set_exception_handler ("My_exception ");
Here, My_expection is a developer-defined exception handling function, which is a top-level exception processor. Only when there is no function in the program to handle exceptions can there be a top-level exception processor to handle exceptions, if the top-level exception processor is not defined, the system's default exception processor will handle the exception.
Example:

The code is as follows: Copy code
<Meta http-equiv = "content-type" content = "text/html; charset = utf-8"/> <? Php
Set_exception_handler ("My_expection ");
Function My_expection (){
Echo "this is a top-level exception processor ";
    }
Try {
Nohello ("hello ");
} Catch (Exception $ e ){
Throw $ e;
    }
Function nohello ($ nohello ){
If ($ nohello = "hello "){
Throw new Exception ("hello cannot be entered ");
} Else {
Echo "input successful ";
        }
    }
?>

 

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.