PHP Error capture processing Exception

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

PHP Error capture processing Exception

Exceptions are used to change the normal flow script if an error is specified



What is an exception
In PHP 5 comes a new object-oriented way to handle errors.

Exception handling is the execution code used to change the normal flow if a particular error (Exception) condition occurs. This condition is called an exception.

This is usually when an exception is triggered:

Current code-saving status
The code execution will switch to the predefined (custom) exception handler function
Depending on the case, the handler can recover the executed code save state, terminate the script execution or resume the script from a different location in the code
We will show different error handling methods:

Basic usage Exceptions
Create a custom exception handling
More exceptions
Throw one more exception.
Setting top-level exception handling
Note: Exceptions should only be used for error conditions and should not be used to jump to another location in the code at a specified point.



Exceptions to basic use
When an exception, the following code will not execute, PHP will try to find a matching "catch" block.

If an exception is not caught, a fatal error will issue a "uncaught exception" message.

Can try to throw an exception without catching it:

<?php
//create function with a exception
function Checknum ($number)
 {
 if ($number >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:webfoldertest.php:6< C2/>stack Trace: #0 c:webfoldertest.php (): 
c:webfoldertest.php6
Try, throw and catch






Grab-This is a "C Atch" block retrieves an exception and creates an object that contains exception information
You can try to trigger an exception-valid code:
<?php
//create function with a exception
function Checknum ($number)
 {
 if ($number >1)
  {
  throw new Exception ("Value must be 1 or below");
  }
 return true;
 }

Trigger exception in a ' try ' block
try
 {
 checknum (2);
 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 above code will get an error like this:

Message:value must be 1 or below
       
       

For example, explain:
The above code throws an exception, capturing it:

The Checknum () function is created. It will check if the number is greater than 1. If so, an exception
The Checknum () function is called a "try" block
The only exception inside the Checknum () function is to throw
Retrives the exception in the catch block and create an object (English) containing exception information
Exception to the error message is the Echo appeal $ e-commerce "getMessage () exception from the object
However, there is a way in which the "every throw must have a catch" rule is to set a top level exception handler to handle the bug slip through the slip.


-------------------------------------------------- ------------------------------

Create a custom exception handling class
Creating a custom exception handler is fairly straightforward. We just create a special class of features that can be said to be an exception when it happens in PHP.

The class must have an extended exception class.

The custom exception handling class inherits the property from the PHP exception handling class, and you can add custom functions to it.

Let's create an exception category:

<?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 The email is not valid
  throw new Customexception ($email);
  }
 
catch (customexception $e)
 {
 //display custom message
 echo $e->errormessage ();
 }
? >

The new category is an addition to the old exception class ErrorMessage () function. Since this is an old class, it inherits the attributes and methods from the old class, we can use the first class method except the exception like return occurrences () and GetFile () and GetMessage ().

For example, explain:
The above code throws an exception, which captures the custom exception class:

The Customexception () creates a first-class extended old exception class. In this way, it inherits all the methods and attributes from the old exception class
The ErrorMessage () function is created. This function returns an error message if the e-mail address is invalid
The dollar's email variable is set to a string, not a valid e-mail address
"Try" to block execution and exceptions, the e-mail address is invalid
An exception to the catch in the Catch block and displays an error message

-------------------------------------------------- ------------------------------

More exceptions
It is possible that the script uses multiple exceptions to check multiple conditions.

You can use something like. Other blocks, a switch, or nest multiple exceptions. These exceptions can use different exception classes and return different error messages:

<?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 ();
 }
? >
          
          

For example, explain:
The above code tests two conditions and throws an exception if any condition is not met:

The Customexception () creates a first-class extended old exception class. In this way, it inherits all the methods and attributes from the old exception class
The ErrorMessage () function is created. This function returns an error message if the e-mail address is invalid
The dollar's email variable is set to a string that is a valid e-mail address, but contains a string "model"
The "Try" block execution and an exception is the primary condition of not throwing
The second condition triggers an exception because the e-mail message contains the string "Role model"
An exception to the catch in the catch block and displays the correct error message
If there is no customexception catch-up, only an exception to the base by-catch, except to be processed there


-------------------------------------------------- ------------------------------

and throw the exception.
Sometimes, when an exception, you might as well handle it differently than the standard way. It is possible to throw an exception for the second time in the "catch" block.

The expected script system error hides the user. System errors may be important to the encoder, but are not of interest to the user. In order for your convenience users to be able to toss the exception with the user-friendly message:

<?php
class Customexception extends Exception
 {public
 function errormessage ()
  {
  //error Message
  $ERRORMSG = $this->getmessage (). ' are 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)
   {
   //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 ();
 }
? >
            
            

For example, explain:
The above code tests if the email address contains a string "role model", if so, except to be thrown again:

The Customexception () creates a first-class extended old exception class. In this way, it inherits all the methods and attributes from the old exception class
The ErrorMessage () function is created. This function returns an error message if the e-mail address is invalid
The dollar's email variable is set to a string that is a valid e-mail address, but contains a string "model"
The "Try" block contains a "try" block that allows it to be removed again
The only exception is to raise the string "role model" from the e-mail message
Exceptions to catches in "catch" blocks and then throw a "customexception"
The "Customexception" is the capture and display of error messages
If the exception is not to grasp the current "try" block, it will seek a catch block of "higher level".


-------------------------------------------------- ------------------------------

Setting top-level exception handling
The Set_exception_handler () function sets a user-defined function to handle all uncaught exceptions.

<?php
function MyException ($exception)
{
echo ' <b>Exception:</b> ', $exception-> GetMessage ();
}
Set_exception_handler (' myexception ');
throw new Exception (' uncaught Exception occurred ');
? >
The output is as follows.
 
  Exception:  uncaught Exception occurred 
 
                
                
above code not There is a "catch" block. Instead, the high-level throws exception handling. This feature should be used to capture the uncaught exception. Exceptions to the





Rule
Code may be surrounded in a try block to help catch potential exceptions
each try block or "throw" must have at least one catch multiple catch can be used to catch exceptions to different classes
Exceptions can be thrown (or thrown back) in a catch block in a try block
A simple rule: if you throw something, you have to catch it.

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.