PHP exception handling Exception class _php skills

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

An exception (Exception) is used to change the normal flow of a script when a specified error occurs. What is an exception? PHP 5 provides a new object-oriented error-handling approach. Exception handling is used to change the normal flow of a script when a specified error (exception) condition occurs. This condition is called an exception. When an exception is triggered, the typically occurs when the current code state is saved code execution is switched to a predefined exception handler function depending on the situation, the processor may restart execution code from the saved code State, terminate the script execution, or continue with the script from another location in the code we will show different error handling methods: Basic use of exceptions create a custom exception handler multiple exceptions to throw exceptions set up the top-level exception handler

The basic use of an exception when the exception is thrown, the subsequent code does not continue, and PHP tries to find a matching "catch" code block. If the exception is not captured and does not use Set_exception_handler () for the appropriate processing, a serious error (fatal error) occurs, and an error message that outputs "uncaught exception" (no exception is caught) is printed. Let's try to throw an exception without capturing it:

1)
 {
 throw new Exception ("Value must be 1 or below");
 }
 return true;
 }
 
Trigger Exception
Checknum (2);
? >

The above code will get an error like this: Fatal error:uncaught exception ' exception ' with message ' Value must is 1 or below ' in C:\webfolder\tes T.php:6 Stack Trace: #0 C:\webfolder\test.php: Checknum () #1 {main} thrown in C:\webfolder\test.php on line 6 Try, t Hrow and catch to avoid errors in the example above, we need to create the appropriate code to handle the exception. The processing handler should include: Try-the function that uses the exception should be in the "try" code block. If no exception is fired, the code continues to execute as usual. However, if the exception is triggered, an exception is thrown. Throw-Here's how to trigger an exception. Each "throw" must correspond to at least one catch catch-"catch" code block catches an exception and creates an object that contains exception information

Let's trigger an exception:

1)
 {
 throw new Exception ("Value must be 1 or below");
 }
 return true;
 }
Fire exception
try
 {
 checknum (2)
 in ' Try ' code block; If the exception is thrown, this text won't be shown
 echo ' If you are here, the number is 1 or below ';
//catch exception
catch (Exception $e)
 {
 echo ' message: '. $e->getmessage ();
>

The code above will get a similar error: Message:value must be 1 or below example explains: The above code throws an exception and captures it:

Create the Checknum () function. It detects if the number is greater than 1. If it is, an exception is thrown. Call the Checknum () function in the "Try" code block. An exception in the Checknum () function is thrown to receive the exception and creates an object ($e) that contains exception information. Output an error message from this exception by calling $e->getmessage () from this exception object

However, to follow the "each throw must correspond to a catch" principle, you can set up a top-level exception handler to handle the missing error. It is easy to create a custom exception handler by creating a custom Exception class. We simply created a special class that called its function when an exception occurred in PHP. The class must be an extension of the exception class.

This custom exception class inherits all the properties of the PHP exception class, and you can add custom functions to it. We started creating the exception class:

Getline (). ' In ' $this->getfile (). ': '. $this->getmessage (). ' isn't 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 The email is not valid
 throw new Customexception ($email)
 ;
 }
 
catch (customexception $e)
 {
 //display custom message
 echo $e->errormessage ();
 }
? >

This new class is a copy of the old exception class, plus the ErrorMessage () function. Because it is a copy of the old class, it inherits properties and methods from the old class, and we can use the methods of the exception class, such as Getline (), GetFile (), and GetMessage (). Example explanation: The above code throws an exception and captures it through a custom exception class: The Customexception () class is created as an extension of the old exception class. So it inherits all the properties and methods of the old class. Create the ErrorMessage () function. If the e-mail address is illegal, the function returns an error message to set the $email variable to an illegal e-mail address string executes a "Try" code block, because the e-mail address is illegal, so throw an exception "catch" code block to catch the exception and display an error message

Multiple exceptions can be used to detect multiple exceptions for a script. You can use multiple if.. else code block, or a switch code block, or nested multiple exceptions. These exceptions can use different exception classes and return different error messages:

Getline (). ' In ' $this->getfile (). '
: '. $this->getmessage (). ' isn't 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 true:

The Customexception () class is created as an extension of the old exception class. So it inherits all the properties and methods of the old class. Create the ErrorMessage () function. If the e-mail address is not valid, the function returns an error message. Executes the "Try" code block, which, under the first condition, does not throw an exception. Because e-mail contains the string "Example", the second condition triggers an exception. The catch code block catches the exception and displays the appropriate error message

If Customexception is not captured, the base exception is tightly captured, where the exception is handled.

Re-throwing an exception sometimes, when an exception is thrown, you might want to handle it in a different way from the standard. You can throw an exception again in a "catch" code block. The script should hide the system error from the user. System errors may be important to programmers, but users are not interested in them. To make the user easier to use, you can throw an exception with a message that is friendly to the user again:

GetMessage (). ' is not a valid e-mail address. '
 return $ERRORMSG;
 }
 
$email = "someone@example.com";
 
Try
 {
 try
 {
 //check for ' example ' in ' Mail address
 if (Strpos ($email, "example")!== FALSE)
 { C12/>//throw exception if email is not valid
 throw new Exception ($email);
 }
 catch (Exception $e)
 {
 //re-throw Exception
 throw new Customexception ($email);
 }
 }
 
catch (customexception $e)
 {
 //display custom message
 echo $e->errormessage ();
 }
? >

Example explanation: The above code detects whether a string "example" is included in the email address. If it does, throw the exception again:

The Customexception () class is created as an extension of the old exception class. So it inherits all the properties and methods of the old class. Create the ErrorMessage () function. If the e-mail address is not valid, the function returns an error message. Set the $email variable to a valid mail address, but contain the string "example". The "Try" code block contains another "try" block of code so that the exception can be thrown again. An exception is triggered because the e-mail contains the string "example". Catch catches the exception and throws "Customexception" again. "Customexception" is captured and an error message is displayed. If the exception is not captured in its current "try" block of code, it looks for a catch code block at a higher level. Set up the top-level exception handler (top level Exception Handler) Set_exception_handler () function to set up a user-defined function that handles all exceptions that are not caught.

GetMessage ();
}
Set_exception_handler (' myexception ');
throw new Exception (' uncaught Exception occurred ');
? >

The output of the above code should look like this: Exception:uncaught Exception occurred in the above code, there is no "catch" code block, but it triggers the top-level exception handler. You should use this function to catch any exceptions that are not caught.

Code that requires exception handling for exception rules should be placed inside a try block to catch potential exceptions. Each try or throw code block must have at least one corresponding catch code block. Multiple catch blocks can be used to catch different kinds of exceptions. You can throw a (re-thrown) exception again in a catch code block within the try code block.

In short: If an exception is thrown, it must be caught.

The above is about the PHP exception handling exception class of all the contents of the introduction, I hope to help you learn.

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.