PHP 5 exception handling, error throws, and callback functions

Source: Internet
Author: User
PHP 5 exception handling, error throws, and callback functions

  1. Error_reporting (E_ALL &~ E_NOTICE); // Other exceptions except E_NOTICE will be triggered (E_ALL &~ The binary operation result of E_NOTICE is: the value of the corresponding bits of E_NOTICE is set to 0. try-catch cannot take effect in the automatic loading function _ autoload () of the class.
  2. Try-catch cannot be used to capture exceptions and cannot catch errors, such as errors triggered by trigger_error (). exceptions and errors are different.
  3. Try {
  4. // You codes that maybe cause an error
  5. } Catch (Exception $ err) {// The type of this error object needs to be declared. Exception is the default Exception handling class of the system.
  6. Echo $ err-> getMessage ();
  7. }

// Thrown can throw an Exception, for example, thrown new Exception ('an error'); an example:

  1. Try {
  2. If (empty ($ var1) throw new NotEmptyException ();
  3. If (empty ($ var2) throw new NotEmptyException ();
  4. If (! Preg_match () throw new InvalidInputException ();
  5. $ Model-> write ();
  6. $ Template-> render ('success ');
  7. } Catch (NotEmptyException $ e ){
  8. $ Template-> render ('error _ empty ');
  9. } Catch (InvalidInputException $ e ){
  10. $ Template-> render ('error _ preg ');
  11. }

Structure of the Exception class: most of the methods are not allowed to be rewritten (final)

  1. Exception {
  2. /* Attribute */
  3. Protected string $ message;
  4. Protected int $ code;
  5. Protected string $ file;
  6. Protected int $ line;
  7. /* Method */
  8. Public _ construct ([string $ message = "" [, int $ code = 0 [, Exception $ previous = null])
  9. Final public string getMessage (void) // information thrown by an exception
  10. Final public Exception getPrevious (void) // previous Exception
  11. Final public int getCode (void) // exception code, which is user-defined
  12. Final public string getFile (void) // file path strength in case of an exception
  13. Final public int getLine (void) // The row with an exception
  14. Final public array getTrace (void) // exception tracking information (array)
  15. Final public string getTraceAsString (void) // exception tracking information (string)
  16. Public string _ toString (void) // The return value of the Subfunction called when an exception object is used as a string.
  17. Final private void _ clone (void) // called when an exception object is cloned
  18. }

The extension exception class try-catch can have multiple catch clauses, starting from the first catch clause. if the exception variable type in the clause matches the exception type thrown by the thrown statement, this clause is executed instead of other catch clauses. Otherwise, the next catch clause will be attempted. because Exception is the base class of all Exception classes, the thrown Exception will match it, if you use different processing methods based on different Exception types, put the catch clause of the Exception type at the end. Exception is the base class of all exceptions. you can extend the Exception class as needed,

  1. Calss MyException extends Exception {
  2. Public errType = 'default ';
  3. Public function _ construct ($ errType = ''){
  4. $ This-> errType = $ errType;
  5. }
  6. }
  7. Thrown new MyException (); // throw an exception
  8. Try {
  9. // You codes that maybe cause an error
  10. } Catch (MyException $ err) {// The type of this error object needs to be declared
  11. Echo $ err-> errType ();
  12. } Catch (ErrorException $ err) {// ErrorException is an Exception class added to PHP 5, inherited from Exception
  13. Echo 'error! ';
  14. } Catch (Exception $ err ){
  15. Redirect ('/error. php ');
  16. }

You may determine the exception type in the catch clause, or decide whether to handle the exception based on the code or other information. if the code you uninstall the catch clause cannot properly handle the caught exception, you can continue to throw an exception in the catch clause.

III. Exception callback function set_exception_handler (callback functionName) // if an Exception occurs or its subclass Exception occurs, the function exceptionHandlerFun ($ errObj) is called) {// The Exception callback function has only one parameter, that is, the thrown Exception object. //.......}

The Exception callback function does not return true as the set_error_handler callback function does. even if the callback function handles exceptions, subsequent code will not be executed, therefore, try-catch is required to continue executing the subsequent code. But there is one exception: the callback function can be executed after the script ends. even if the thrown exception is not processed, the callback function can also be executed. Register_shutdown_function (callback functionName [, argument1, argument2,...]); example:

  1. Function shutdownfunction (){

  2. Echo 'script is end ';
  3. }

  4. Register_shutdown_function ("shutdownfunction ");

Because shutdownfunction () is executed at the end of the script, the function at any position in the script can be called in this callback function, even if the function is defined after the error throw position (the function definition is completed during the script compilation period ).

4. trigger_error (string errorMsg [, int user_error_type]) This function is used to actively trigger an error: user_error_type can only be E_ALL, E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE, or its combination value. Set_error_handler (callbeck functionName [, user_error_type]); // set a callback function for trigger_error () to handle errors, including system errors and errors triggered by users using the trigger_error () function.

Optional parameter user_error_type: If this parameter is set, the error type thrown by trigger_error must be within the defined range of user_error_type to trigger the callback function. The setting of this value is similar to the error_reporting () function.

The first parameter (callbeck functionName) is a function name, which can have five parameters. The first two parameters are required: user_error_type thrown by trigger_error, errorMsg thrown by trigger_error, absolute path strength of the file that throws the error, row number that throws the error, and context environment when the error is thrown (an array containing trigger_error () return value of the callback function: if false is returned, the system error processing mechanism continues to throw this error, if true is returned or no return value is returned, the error is eliminated. Errors triggered by trigger_error () are not caught by the try-catch exception capture statement.

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.