PHP exception Handling related knowledge

Source: Internet
Author: User
Tags learn php php error php exception handling stack trace throw exception
    1. Create function with an exception
    2. function Checknum ($number)
    3. {
    4. if ($number >1)
    5. {
    6. throw new Exception ("Value must be 1 or below");
    7. }
    8. return true;
    9. }
    10. Trigger exception
    11. Checknum (2);
    12. ?>
Copy Code

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 the error in the above example, 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 triggered, the code will continue to execute as usual. However, if an exception is triggered, an exception is thrown. Throw-this specifies how the exception is triggered. Each "throw" must correspond to at least one catch catch-the "catch" code block catches the exception and creates an object containing the exception information

Let's trigger an exception:

    1. To create a function that throws an exception
    2. function Checknum ($number)
    3. {
    4. if ($number >1)
    5. {
    6. throw new Exception ("Value must be 1 or below");
    7. }
    8. return true;
    9. }
    10. To trigger an exception in a "try" code block
    11. Try
    12. {
    13. Checknum (2);
    14. If the exception is thrown, this text would not be shown
    15. Echo ' If You see this, the number is 1 or below ';
    16. }
    17. Catching exceptions
    18. catch (Exception $e)
    19. {
    20. Echo ' Message: '. $e->getmessage ();
    21. }
    22. ?>
Copy Code

The above code will get a similar error: Message:value must be 1 or below example explanation: 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. The exception in the Checknum () function is thrown by a "catch" code block that receives the exception and creates an object ($e) that contains the exception information. Output the error message from this exception by calling $e->getmessage () from this exception object

However, to follow the principle that each throw must correspond to a catch, you can set up a top-level exception handler to handle the missing error. Creating a custom Exception class creates a custom exception handler that is very simple. We have simply created a special class that can call its function when an exception occurs 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 to create the exception class:

    1. Class Customexception extends Exception
    2. {
    3. Public Function ErrorMessage ()
    4. {
    5. Error message
    6. $ERRORMSG = ' Error on line '. $this->getline (). ' In '. $this->getfile ()
    7. . ': '. $this->getmessage (). ' is not a valid e-mail address ';
    8. return $ERRORMSG;
    9. }
    10. }
    11. $email = "someone@example...com";
    12. Try
    13. {
    14. Check if
    15. if (Filter_var ($email, filter_validate_email) = = = FALSE)
    16. {
    17. Throw exception if email is not valid
    18. throw new Customexception ($email);
    19. }
    20. }
    21. catch (Customexception $e)
    22. {
    23. Display custom Message
    24. echo $e->errormessage ();
    25. }
    26. ?>
Copy Code

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 not valid, then the function returns an error message that sets the $email variable to an illegal e-mail address string to execute a "try" block of code, because the e-mail address is not valid, so throw an exception "catch" code block catch exception, and display an error message

Multiple exceptions

You can use multiple exceptions for a script to detect multiple situations.

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:

  1. Class Customexception extends Exception
  2. {
  3. Public Function ErrorMessage ()
  4. {
  5. Error message
  6. $ERRORMSG = ' Error on line '. $this->getline (). ' In '. $this->getfile ()
  7. . ': '. $this->getmessage (). ' is not a valid e-mail address ';
  8. return $ERRORMSG;
  9. }
  10. }
  11. $email = "someone@example.com";
  12. Try
  13. {
  14. Check if
  15. if (Filter_var ($email, filter_validate_email) = = = FALSE)
  16. {
  17. Throw exception if email is not valid
  18. throw new Customexception ($email);
  19. }
  20. Check for "Example" in mail address
  21. if (Strpos ($email, "example")!== FALSE)
  22. {
  23. throw new Exception ("$email is an example e-mail");
  24. }
  25. }
  26. catch (Customexception $e)
  27. {
  28. echo $e->errormessage ();
  29. }
  30. catch (Exception $e)
  31. {
  32. echo $e->getmessage ();
  33. }
  34. ?>
Copy Code

Example explanation: The above code tests two conditions, and throws an exception if any condition is 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 a "try" block of code that, under the first condition, does not throw an exception. Because e-mail contains the string "Example", the second condition triggers an exception. Catch code block catches exceptions and displays appropriate error messages

If the customexception is not captured and the base exception is tightly captured, the exception is handled there. To re-throw 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. For programmers, system errors may be important, but users are not interested in them. To make it easier for users to use, you can again throw an exception with a friendly message to the user:

  1. Class Customexception extends Exception
  2. {
  3. Public Function ErrorMessage ()
  4. {
  5. Error message
  6. $ERRORMSG = $this->getmessage (). ' is not a valid e-mail address. ';
  7. return $ERRORMSG;
  8. }
  9. }
  10. $email = "someone@example.com";
  11. Try
  12. {
  13. Try
  14. {
  15. Check for "Example" in mail address
  16. if (Strpos ($email, "example")!== FALSE)
  17. {
  18. Throw exception if email is not valid
  19. throw new Exception ($email);
  20. }
  21. }
  22. catch (Exception $e)
  23. {
  24. Re-throw exception
  25. throw new Customexception ($email);
  26. }
  27. }
  28. catch (Customexception $e)
  29. {
  30. Display custom Message
  31. echo $e->errormessage ();
  32. }
  33. ?>
Copy Code

Example explanation: The above code detects if a string "example" is included in the email address. If so, throws 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 e-mail address, but contains the string "example". The "Try" code block contains another "try" code block so that you can throw the exception again. The exception is triggered because e-mail contains the string "example". Catch catches the exception and re-throws "Customexception". "Customexception" is captured and an error message is displayed.

If an exception is not caught in its current "try" code block, it looks for a catch code block at a higher level.

Setting the top level exception processor (top Exception Handler)

The Set_exception_handler () function sets a user-defined function to handle all uncaught exceptions.

    1. function MyException ($exception)
    2. {
    3. echo "Exception: ", $exception->getmessage ();
    4. }
    5. Set_exception_handler (' myexception ');
    6. throw new Exception (' uncaught Exception occurred ');
    7. ?>
Copy Code

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 the top-level exception handler is triggered. You should use this function to catch all uncaught exceptions. The exception rule code that requires exception handling should be placed inside a try code block to catch a potential exception. Each try or throw code block must have at least one corresponding catch code block. You can use multiple catch blocks to catch different kinds of exceptions. You can throw (re-thrown) exceptions again in a catch code block within a try code block.

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

Source: http://bbs.it-home.org/w3school/php/php_exception.html

Instance:

  1. function Throwtest ($data)
  2. {
  3. Try
  4. {
  5. if (!is_array ($data) | | emptyempty ($DATA))
  6. {
  7. throw new Exception (' The type of the data is not an array ', 445);
  8. }
  9. Echo (' Finish in order to test!! ');
  10. }
  11. catch (Exception $e)
  12. {
  13. /*echo ' error message: ', $e->getmessage (), '
    ';//error message
  14. Echo '
    Error code: ', $e->getcode (), '
    ';//error code
  15. Echo '
    Error file: ', $e->getfile (), '
    ';//Error file
  16. Echo '
    Error line number: ', $e->getline (), '
    ';//Error line number
  17. Echo '
    The error message is shown in an array: ', Print_r ($e->gettrace ()), '
    ';//The error message is shown in an array
  18. Echo '
    The error message is displayed as a string: ', $e->gettraceasstring (), '
    ';//The error message is displayed as a string */
  19. echo $e->getmessage (), '
    ';//error message
  20. Echo '
    ', $e->gettraceasstring (), '
    ';//The error message is displayed as a string
  21. Exit
  22. }
  23. }
  24. $data =array ("111", "33333"); Normal test
  25. $data = "8129233"; Anomaly Testing
  26. Throwtest ($data);
  27. ?>
Copy Code

You may be interested in the article: Using PHP Exception Handling Class Exception example PHP5 exception handling, error throwing and callback functions PHP exception handling, error throwing and error callback function a simple PHP custom exception class to learn PHP error and exception settings

  • 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.