The use of exception exception handling classes in PHP _php tutorial

Source: Internet
Author: User
Tags throw exception
This article introduced in PHP commonly used in the simple exception processing class, we mainly describe the exception processing, there is a need to understand the students can refer to.
The code is as follows Copy Code
try {
$a =10/0;
}catch (Exception $e) {
echo "Throws Exception";
}
?>

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

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

So can catch the exception, depending on whether there is a real throw exception

code as follows copy code

"!--? php
class Exception
{ protected $message = ' Unknown exception '; Exception information
Protected $code = 0;//user-defined exception code
protected $file;//file name of the exception
protected $line;//code line number of the exception

Fu Nction __construct ($message = null, $code = 0);

Final function getMessage ();//Return exception Information
Final function getcode ();//Return Exception Code
final function GetFile ();//Return exception occurred The file name
Final function getLine ();//Returns the code line number where the exception occurred
Final function gettrace ();//BackTrace () array
Final function Gett Raceasstring (); Gettrace () information that has been rasterized into a string

/* Overloaded method */
function __tostring ();//output String
}
?

The simple use is as follows: (by exception, throw an error message)

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 to facilitate our use of

copy code

Class MyException extends Exception
{
The redefine constructor makes the message a property that must be specified
Public function __construct ($message, $code = 0) {
//Custom code

//Ensure that all variables are correctly assigned br> parent::__construct ($message, $code);
}

//Custom string output style
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 code is invoked to execute in the try code. If there is an error in the try code block, we can perform a handling of throwing exceptions. Some programming languages, such as Java, will automatically throw exceptions in certain situations. In PHP, exceptions must be thrown manually. You can throw an exception using the following method:

The code is as follows Copy Code

Throw New Exception (' message ', code);

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

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

The code is as follows Copy Code

Catch (Exception $e)

{

Handing exception

}

The catch code captures an object that causes an exception and is passed to the throw statement (thrown by a throw statement). Using an instance of the exception class is a good choice.

The exception class provides the following built-in methods:

GetCode ()-Returns the code passed to the constructor.

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

GetFile ()-Returns the path to the file that generated the exception code

GetLine ()-Returns the line that contains the code that generated the exception.
Attention:

When an exception is caught, subsequent code inside the try () block will not continue, but will attempt to find a matching "catch" block of code
When an exception is thrown, the "uncaught exception ' exception '" error is reported if no catch is processed

The code is as follows Copy Code
function test ($val) {
if ($val >100) {
throw new Exception ("Prompt message: You have entered a value too large");
}
}
Test (111);
?>

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

Here are some of the code for my user registration feature

try{
Check forms filled in
if (!filled_out ($_post)) {
throw new Exception (' You have not filled out the form, please go back and fill in ');
}
Check email Address not valid
if (!check_email ($email)) {
throw new Exception (' The message is not in the correct format ');
}
Check if the length of the density is greater than 6
if (strlen ($passwd <6)) {
throw new Exception (' The length of the density should be greater than 6 ');
}
Check two times if the password is equal
if ($passwd! = $passwd 1) {
throw new Exception (' Two password is not the same, please re-enter ');
}
Check if the user name is the correct length
if (strlen ($username) >16) {
throw new Exception (' The length of the user name does not match, please re-enter ');
}

} catch (Exception $e) {
echo $e->getmessage (); Output exception information.
}

PHP handles exceptions like Java, with Try{}catch () {}

The function used to define the top-level exception handler is
Set_exception_handler ("My_exception");
The my_expection here is a developer-defined exception handler, a top-level exception processor that handles exceptions only if there are no functions in the program to handle exceptions, and if the top-level exception handler is not defined, the system defaults the exception handler to handle the exception
To illustrate:

The code is as follows Copy Code
Set_exception_handler ("My_expection");
function My_expection () {
echo "Here is the top exception processor";
}
try{
Nohello ("Hello");
}catch (Exception $e) {
Throw $e;
}
function Nohello ($nohello) {
if ($nohello = = "Hello") {
throw new Exception ("Cannot enter Hello");
}else{
echo "Input Success";
}
}
?>

http://www.bkjia.com/PHPjc/631616.html www.bkjia.com true http://www.bkjia.com/PHPjc/631616.html techarticle This article introduced in PHP commonly used in the simple exception processing class, we mainly describe the exception processing, there is a need to understand the students can refer to. Code to copy code like this? ph ...

  • Related Article

    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.