Home  >  Article  >  Backend Development  >  Exception handling, error throwing and error callback functions in php

Exception handling, error throwing and error callback functions in php

WBOY
WBOYOriginal
2016-07-25 09:03:531247browse
  1. try{

  2. // you codes that maybe cause an error

  3. }catch(Exception $err){ // This error object needs to declare the type, Exception is The system default exception handling class

  4. echo $err->getMessage();
  5. }

  6. //thrown can throw an exception, such as:

  7. thrown new Exception('an error');

Copy code

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

Copy code

The structure of the Exception class: most of its methods are prohibited from being overridden (final) Exception { /* Attributes */ protected string $message; protected int $code; protected string $file; protected int $line; /* method */ public __construct ([ string $message = "" [, int $code = 0 [, Exception $previous = null]]] ) final public string getMessage (void) //Message thrown by exception final public Exception getPrevious (void) //Previous exception final public int getCode (void) //Exception code, this is user-defined final public string getFile (void) //The file path where the exception occurred final public int getLine (void) //The line where the exception occurred final public array getTrace (void) //Exception tracking information (array) final public string getTraceAsString (void) //Exception tracking information (string) public string __toString (void) //The return value of calling a subfunction when trying to use the exception object directly as a string final private void __clone (void) //Called when cloning an exception object }

Extended 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 throw statement, the clause will be executed and no other catch will be executed. clause, otherwise continue to try the next catch clause. Since Exception is the base class of all exception classes, the exceptions thrown will match it. If you need to use different processing methods according to different exception types, you should use the Exception type catch The clause is placed last.

Exception is the base class of all exceptions, and the exception class can be extended according to actual needs

  1. calss MyException extends Exception{

  2. public errType = 'default';
  3. public function __construct($errType=''){
  4. $this->errType = $errType;
  5. }
  6. }

  7. try{ // you codes that maybe cause an error

  8. thrown new MyException('an error');
  9. }catch(MyException $err){ // This error object needs to declare the type
  10. echo $err->errType();
  11. }catch(ErrorException $err){ //ErrorException is an exception class added in PHP 5, inherited from Exception
  12. echo 'error !';
  13. }catch(Exception $err){
  14. redirect('/error.php');
  15. }

Copy code

You may determine the type of exception in the catch clause, or decide whether to handle the exception based on code and other information , if the code you unload the catch clause cannot properly handle the caught exception, you can continue to throw exceptions within the catch clause. 3. Exception callback function set_exception_handler(callback functionName) //This function will be called when an exception of Exception or its subclass occurs function exceptionHandlerFun($errObj){ // Exception exception callback function has only one parameter, which is the thrown exception object. //....... }

Exception exception callback function cannot eliminate the exception by returning true like set_error_handler's callback function. Even if the callback function handles the exception, subsequent code will not continue to be executed, so if you want to continue executing subsequent code, try-catch must be used .

But there is an exception: the script end callback function can be executed, and the callback function can be executed even if the thrown exception is not handled. register_shutdown_function(callback functionName[,argument1,argument2,...]);

For example:

  1. function shutdownfunction(){
  2. echo 'script is end';
  3. }
  4. register_shutdown_function("shutdownfunction");
Copy code

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

4. trigger_error(string errorMsg[,int user_error_type]) This function is used to actively trigger an error: user_error_type can only be the value of E_ALL, E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE or a combination thereof.

set_error_handler(callback functionName[,user_error_type]); //Set a callback function for trigger_error() to handle errors, including errors thrown by the system and errors triggered by the user using the trigger_error() function.

Optional parameter user_error_type: If this parameter is set, the callback function can be triggered only when the error type thrown by trigger_error matches the definition range of user_error_type. This value is set similarly to the error_reporting() function.

First parameter (callbeck functionName): A function name. The function can have 5 parameters, of which the first 2 are required, in order: The user_error_type that trigger_error throws, the errorMsg that trigger_error throws, the absolute path of the file that throws the error, the line number that throws the error, and the context when the error is thrown (an array that contains everything in the scope where trigger_error() is located. Variables, functions, classes and other data)

Return value of the callback function: If false is returned, the system error handling mechanism will continue to throw the error, and return true or no return value to eliminate the error. Errors triggered by trigger_error() will not be caught by try-catch exception catching statements. Articles you may be interested in: Knowledge related to PHP exception handling Example of using php exception handling class Exception Exception handling, error throwing and error callback functions in php A simple php custom exception class Learn php errors and exception settings



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn