PHP exception handling-php Tutorial

Source: Internet
Author: User
Tags php exception handling valid email address
PHP exception handling knowledge

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

The above code will get an error similar to this: Fatal error: Uncaught exception 'exception' with message 'value must be 1 or below 'in C: \ webfolder \ test. php: 6 Stack trace: #0 C: \ webfolder \ test. php (12): checkNum (28) #1 {main} thrown in C: \ webfolder \ test. php on line 6 Try, throw, and catch to avoid errors in the above example, we need to create appropriate code to handle exceptions.

The handler should include: Try-use abnormal functions should be located in the "try" code block. If no exception is triggered, the code continues as usual. However, if an exception is triggered, an exception is thrown. Throw-This specifies how to trigger an exception. Each "throw" must correspond to at least one "catch" Catch-"catch" code block to capture exceptions and create an object containing exception information.

Let's trigger an exception:

  1. // Create a function that can throw 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 an exception in the try code block
  11. Try
  12. {
  13. CheckNum (2 );
  14. // If the exception is thrown, this text will not be shown
  15. Echo 'If you see this, the number is 1 or below ';
  16. }
  17. // Capture exceptions
  18. Catch (Exception $ e)
  19. {
  20. Echo 'message: '. $ e-> getMessage ();
  21. }
  22. ?>

The code above will get an error similar to this: Message: Value must be 1 or below example explanation: the code above throws an exception and captures it: creates the checkNum () function. It checks whether the number is greater than 1. If yes, an exception is thrown. Call the checkNum () function in the "try" code block. An exception in the checkNum () function is thrown. the "catch" code block receives the exception and creates an object containing the exception information ($ e ). Call $ e-> getMessage () from this exception object to output error messages from this exception.

However, to follow the "each throw must correspond to a catch" principle, you can set a top-level exception processor to handle missed errors. It is very easy to create a custom Exception handler for the custom Exception class. We have simply created a special class. When an exception occurs in PHP, we can call its function. This class must be an extension of the exception class.

This custom exception class inherits all attributes of the PHP exception class. you can add custom functions to it.

Let's start 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 M message
  24. Echo $ e-> errorMessage ();
  25. }
  26. ?>

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 attributes and methods from the old class. we can use methods of the exception class, such as getLine () and getFile () and getMessage (). The preceding 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. In this way, it inherits all the attributes and methods of the old class. Create the errorMessage () function. If the email address is invalid, this function returns an error message and sets the $ email variable to an invalid email address string to execute the "try" code block, because the email address is invalid, an exception "catch" code block is thrown to capture the exception and an error message is displayed.

Multiple exceptions

Multiple exceptions can be used for a script to detect multiple cases.

You can use multiple if. else code blocks, a switch code block, or nested 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. ?>

The preceding code tests two conditions. if any condition is not true, an exception is thrown: the customException () class is created as an extension of the old exception class. In this way, it inherits all the attributes and methods of the old class. Create the errorMessage () function. If the email address is invalid, this function returns an error message. Execute the "try" code block. under the first condition, no exception is thrown. Because e-mail contains the string "example", the second condition triggers an exception. The "catch" code block captures exceptions and displays appropriate error messages.

If the base mexception is not captured and the base exception is captured tightly, the exception is handled there. Throw an exception again.

Sometimes, when an exception is thrown, you may want to handle it in a different way than the standard. You can throw an exception again in a "catch" code block.

The script should hide system errors from users. For programmers, system errors may be important, but users are not interested in them. To make it easier for users to use, you can throw an exception with user-friendly messages again:

  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 M message
  31. Echo $ e-> errorMessage ();
  32. }
  33. ?>

The preceding code checks whether the email address contains the string "example ". If yes, an exception is thrown again: the customException () class is created as an extension of the old exception class. In this way, it inherits all the attributes and methods of the old class. Create the errorMessage () function. If the email address is invalid, this function returns an error message. Set the $ email variable to a valid email address, but it contains the string "example ". The "try" code block contains another "try" code block, so that an exception can be thrown again. An exception is triggered because e-mail contains the string "example. "Catch" captures this exception and throws "customException" again ". Capture "customException" and display an error message.

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

Top Level Exception Handler)

The set_exception_handler () function can be used to process all user-defined functions without capturing 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. ?>

The output of the above code should be similar to this: Exception: Uncaught Exception occurred. in the above code, the "catch" code block does not exist, but triggers the Exception handler at the top layer. This function should be used to capture all exceptions that are not captured. Code that requires exception handling for exception rules should be placed in the try code block to capture potential exceptions. Each try or throw code block must have at least one catch code block. Multiple catch code blocks can capture different types of exceptions. You can throw a (re-thrown) exception again in the catch code block in the try code block.

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

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 ('data type is not an array', 445 );
  8. }
  9. Echo ('done for 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 row number: ', $ e-> getLine (),'
    '; // Error row number
  17. Echo'
    The error message is displayed in an array: ', print_r ($ e-> getTrace ()),'
    '; // The error message is displayed 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"; // exception test
  26. ThrowTest ($ data );
  27. ?>

Articles you may be interested in: example of php Exception handling exceptions: php P5 Exception handling, error throws, callback functions, and other php Exception handling, error throws, and error callback functions. a simple php custom Exception class learn php errors and exception settings

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.