Home  >  Article  >  php教程  >  PHP exception handling, error throwing and error callback functions

PHP exception handling, error throwing and error callback functions

WBOY
WBOYOriginal
2016-07-09 09:08:04956browse

1. Error and exception level constant table

error: A runtime error that cannot be found during compilation. It is better to try to use echo to output an unassigned variable. Such problems often cause the program or logic to be unable to continue and need to be interrupted;

Exception: An unexpected situation occurs during the execution of the program. Logically, it often works, but it does not meet the application scenario. For example, a user name whose length exceeds the predetermined format is received. Therefore, the exception mainly depends on the coder. Make a pre-judgement and then throw it. After catching the exception, change the program flow to handle these situations without interrupting the program.

PHP’s definition of exceptions and errors does not seem to be very obvious, especially in lower versions of PHP.

Error and logging values                                                                                                  Remarks1 E_ERROR (integer) Fatal runtime error. ​ ​ ​ |This type of error is generally an unrecoverable situation, such as a problem caused by memory allocation. The consequence is that the script terminates and does not continue to run. 2 E_WARNING (integer) Runtime warning (non-fatal error). |Only a prompt message is given, but the script does not terminate.
4 E_PARSE (integer) Compile-time syntax parsing error. |Parse errors are generated only by the parser.

8 E_NOTICE (integer) Runtime notification.                                                                                                                                                                                                                               Indicates that the script encounters a situation that may appear as an error, but there may also be similar notifications in scripts that can run normally.

16 E_CORE_ERROR(integer) Fatal error occurred during PHP initialization and startup. |This error is similar to E_ERROR, but is generated by the PHP engine core. since PHP 4

32 E_CORE_WARNING(integer) Warning (non-fatal error) that occurred during PHP initialization startup. |Similar to E_WARNING, but generated by the PHP engine core. since PHP 4

64 E_COMPILE_ERROR(integer) Fatal compile-time error. |Similar to E_ERROR, but generated by the Zend script engine. since PHP 4

128 E_COMPILE_WARNING(integer) Compile time warning (non-fatal error). |Similar to E_WARNING, but generated by the Zend scripting engine. since PHP 4

256 E_USER_ERROR(integer) Error message generated by the user. |Similar to E_ERROR, but is generated by the user using the PHP function trigger_error() in the code. since PHP 4

512 E_USER_WARNING(integer) Warning message generated by the user. |Similar to E_WARNING, but generated by the user using the PHP function trigger_error() in the code. since PHP 4

1024 E_USER_NOTICE(integer) Notification information generated by the user. |Similar to E_NOTICE, but generated by the user using the PHP function trigger_error() in the code. since PHP 4

2048 E_STRICT (integer) Enable PHP's suggestions for code modifications. |Ensure code has optimal interoperability and forward compatibility, since PHP 5

4096 E_RECOVERABLE_ERROR(integer) Fatal error that can be caught. |It indicates that a potentially dangerous error has occurred, but has not yet caused the PHP engine to be in an unstable state. If the error is not caught by a user-defined handle (see See set_error_handler()), will become an E_ERROR and the script will terminate. since PHP 5.2.0

8192 E_DEPRECATED(integer) Runtime notification. | After enabling, a warning will be given to the code that may not work properly in the future version. since PHP 5.3.0

16384 E_USER_DEPRECATED(integer) Warning message for low household assets. |Similar to E_DEPRECATED, but generated by the user using the PHP function trigger_error() in the code. since PHP 5.3.0

30719 E_ALL (integer) E_STRICT All error and warning messages outgoing.

*30719 in PHP 5.3.x, 6143 in PHP 5.2.x, 2047 previously

2. error_reporting() and try-catch, thrown

The error_reporting() function can obtain (when no parameters are passed) and set which exceptions the script handles (not all exceptions need to be handled, such as E_CORE_WARNING, E_NOTICE, and E_DEPRECATED can be ignored). This setting will override php.ini Exception handling settings defined in the error_reporting option.

For example:

<span style="color: #008080;" data-mce-mark="1">error_reporting</span>(<span style="color: #ff00ff;" data-mce-mark="1">E_ALL</span>&~<span style="color: #ff00ff;" data-mce-mark="1">E_NOTICE</span>) ; <span style="color: #008000;" data-mce-mark="1">//</span><span style="color: #008000;" data-mce-mark="1"> 除了E_NOTICE其他异常都会被触发 (E_ALL&~E_NOTICE 的二进制运算结果是:E_NOTICE对应位的值被设置为0,应注意到,错误和日志记录值都是一个二进制数,某一位设置为1)</span>

try-catch cannot take effect within the autoloading function __autoload() of the class.

try-catch is used to catch exceptions. Errors cannot be caught, such as errors triggered by trigger_error(). Exceptions and errors are different.

PHP exception handling, error throwing and error callback functions
<span style="color: #0000ff;">try</span><span style="color: #000000;">{

  </span><span style="color: #008000;">//</span><span style="color: #008000;"> you codes that maybe cause an error</span>
<span style="color: #000000;">
}</span><span style="color: #0000ff;">catch</span>(<span style="color: #0000ff;">Exception</span> <span style="color: #800080;">$err</span>){ <span style="color: #008000;">//</span><span style="color: #008000;"> 这个错误对象需要声明类型, Exception 是系统默认异常处理类</span>

    <span style="color: #0000ff;">echo</span> <span style="color: #800080;">$err</span>-><span style="color: #000000;">getMessage();

}

 

</span><span style="color: #008000;">//</span><span style="color: #008000;">thrown 可以抛出一个异常,如:</span>
<span style="color: #000000;">
thrown </span><span style="color: #0000ff;">new</span> <span style="color: #0000ff;">Exception</span>('an error');
PHP exception handling, error throwing and error callback functions

An example:

PHP exception handling, error throwing and error callback functions
<span style="color: #0000ff;">try</span><span style="color: #000000;"> {

    </span><span style="color: #0000ff;">if</span> ( <span style="color: #0000ff;">empty</span>( <span style="color: #800080;">$var1</span> ) ) <span style="color: #0000ff;">throw</span> <span style="color: #0000ff;">new</span><span style="color: #000000;"> NotEmptyException();
    </span><span style="color: #0000ff;">if</span> ( <span style="color: #0000ff;">empty</span>( <span style="color: #800080;">$var2</span> ) ) <span style="color: #0000ff;">throw</span> <span style="color: #0000ff;">new</span><span style="color: #000000;"> NotEmptyException();
    </span><span style="color: #0000ff;">if</span> ( ! <span style="color: #008080;">preg_match</span>() ) <span style="color: #0000ff;">throw</span> <span style="color: #0000ff;">new</span><span style="color: #000000;"> InvalidInputException();

    </span><span style="color: #800080;">$model</span>-><span style="color: #000000;">write();
    </span><span style="color: #800080;">$template</span>->render( 'success'<span style="color: #000000;"> );
  
} </span><span style="color: #0000ff;">catch</span> ( NotEmptyException <span style="color: #800080;">$e</span><span style="color: #000000;"> ) {

  </span><span style="color: #800080;">$template</span>->render( 'error_empty'<span style="color: #000000;"> );

} </span><span style="color: #0000ff;">catch</span> ( InvalidInputException <span style="color: #800080;">$e</span><span style="color: #000000;"> ) {

  </span><span style="color: #800080;">$template</span>->render( 'error_preg'<span style="color: #000000;"> );

}</span>
PHP exception handling, error throwing and error callback functions

Exception class structure: most of the methods are prohibited from being overridden (final)

PHP exception handling, error throwing and error callback functions
<span style="color: #0000ff;">Exception</span><span style="color: #000000;"> {
</span><span style="color: #008000;">/*</span><span style="color: #008000;"> 属性 </span><span style="color: #008000;">*/</span>
<span style="color: #0000ff;">protected</span> <span style="color: #0000ff;">string</span> <span style="color: #800080;">$message</span><span style="color: #000000;"> ;
</span><span style="color: #0000ff;">protected</span> int <span style="color: #800080;">$code</span><span style="color: #000000;"> ;
</span><span style="color: #0000ff;">protected</span> <span style="color: #0000ff;">string</span> <span style="color: #800080;">$file</span><span style="color: #000000;"> ;
</span><span style="color: #0000ff;">protected</span> int <span style="color: #800080;">$line</span><span style="color: #000000;"> ;
</span><span style="color: #008000;">/*</span><span style="color: #008000;"> 方法 </span><span style="color: #008000;">*/</span>
<span style="color: #0000ff;">public</span> __construct ([ <span style="color: #0000ff;">string</span> <span style="color: #800080;">$message</span> = "" [, int <span style="color: #800080;">$code</span> = 0 [, <span style="color: #0000ff;">Exception</span> <span style="color: #800080;">$previous</span> = <span style="color: #0000ff;">null</span><span style="color: #000000;">]]] )
</span><span style="color: #0000ff;">final</span> <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">string</span> getMessage ( void ) <span style="color: #008000;">//</span><span style="color: #008000;">异常抛出的信息</span>
<span style="color: #0000ff;">final</span> <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">Exception</span> getPrevious ( void ) <span style="color: #008000;">//</span><span style="color: #008000;">前一异常</span>
<span style="color: #0000ff;">final</span> <span style="color: #0000ff;">public</span> int getCode ( void ) <span style="color: #008000;">//</span><span style="color: #008000;">异常代码,这是用户自定义的</span>
<span style="color: #0000ff;">final</span> <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">string</span> getFile ( void ) <span style="color: #008000;">//</span><span style="color: #008000;">发生异常的文件路劲</span>
<span style="color: #0000ff;">final</span> <span style="color: #0000ff;">public</span> int getLine ( void ) <span style="color: #008000;">//</span><span style="color: #008000;">发生异常的行</span>
<span style="color: #0000ff;">final</span> <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">array</span> getTrace ( void ) <span style="color: #008000;">//</span><span style="color: #008000;">异常追踪信息(array)</span>
<span style="color: #0000ff;">final</span> <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">string</span> getTraceAsString ( void ) <span style="color: #008000;">//</span><span style="color: #008000;">异常追踪信息(string)</span>
<span style="color: #0000ff;">public</span> <span style="color: #0000ff;">string</span> __toString ( void ) <span style="color: #008000;">//</span><span style="color: #008000;">试图直接 将异常对象当作字符串使用时调用子函数的返回值</span>
<span style="color: #0000ff;">final</span> <span style="color: #0000ff;">private</span> void __clone ( void ) <span style="color: #008000;">//</span><span style="color: #008000;">克隆异常对象时调用</span>
}
PHP exception handling, error throwing and error callback functions

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 thrown statement, the clause will be executed and no longer executed. Other catch clauses, 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 change the Exception type The catch clause is placed last.

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

PHP exception handling, error throwing and error callback functions
calss MyException <span style="color: #0000ff;">extends</span> <span style="color: #0000ff;">Exception</span><span style="color: #000000;">{
   </span><span style="color: #0000ff;">public</span> errType = 'default'<span style="color: #000000;">;
   </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span> __construct(<span style="color: #800080;">$errType</span>=''<span style="color: #000000;">){
      </span><span style="color: #800080;">$this</span>->errType = <span style="color: #800080;">$errType</span><span style="color: #000000;">;
  }

}
 


</span><span style="color: #0000ff;">try</span>{  <span style="color: #008000;">//</span><span style="color: #008000;"> you codes that maybe cause an error</span>
   thrown <span style="color: #0000ff;">new</span> MyException('an error'<span style="color: #000000;">);
}</span><span style="color: #0000ff;">catch</span>(MyException <span style="color: #800080;">$err</span>){ <span style="color: #008000;">//</span><span style="color: #008000;"> 这个错误对象需要声明类型 </span>
   <span style="color: #0000ff;">echo</span> <span style="color: #800080;">$err</span>-><span style="color: #000000;">errType(); 
}</span><span style="color: #0000ff;">catch</span>(ErrorException <span style="color: #800080;">$err</span>){ <span style="color: #008000;">//</span><span style="color: #008000;">ErrorException 是 PHP 5 增加的异常类以便将错误封装为异常,可以更好地处理错误信息,继承于 Exception</span>
   <span style="color: #0000ff;">echo</span> 'error !'<span style="color: #000000;">; 
}</span><span style="color: #0000ff;">catch</span>(<span style="color: #0000ff;">Exception</span> <span style="color: #800080;">$err</span><span style="color: #000000;">){
   redirect(</span>'/error.php'<span style="color: #000000;">);
 }</span>
PHP exception handling, error throwing and error callback functions

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 write in the catch clause cannot properly handle the caught exception, you can use the catch clause Continue to throw an exception.

3. Exception callback function

PHP exception handling, error throwing and error callback functions
<span style="color: #008080;">set_exception_handler</span>('exceptionHandlerFun')  <span style="color: #008000;">//</span><span style="color: #008000;">发生 Exception 或其 子类的 异常是会调用此函数</span>

<span style="color: #0000ff;">function</span> exceptionHandlerFun(<span style="color: #800080;">$errObj</span>){  <span style="color: #008000;">//</span><span style="color: #008000;"> Exception 异常的回调函数 只有一个参数,就是抛出的异常对象。

 //.......</span>
<span style="color: #000000;">
}</span>
PHP exception handling, error throwing and error callback functions

 

 Exception 异常的回调函数并不能像  set_error_handler 的回调函数那样通过返回 true 来使异常被消除,即使回调函数处理了异常,后继代码也不会被继续执行,因此想继续执行后续代码必须使用 try-catch,在 try-catch 内被捕获的异常不会触发 exception_handler

 

但是有一个例外:抛出的异常即使没有被处理,脚本结束回调函数可以被执行。

 

register_shutdown_function(callback functionName[,argument1,argument2,...]);

例如:

PHP exception handling, error throwing and error callback functions
<span style="color: #0000ff;">function</span><span style="color: #000000;"> shutdownfunction(){

    </span><span style="color: #0000ff;">echo</span> 'script is end'<span style="color: #000000;">;

}

</span><span style="color: #008080;">register_shutdown_function</span>("shutdownfunction"); 
PHP exception handling, error throwing and error callback functions

 

因为 shutdownfunction() 在脚本结束时被执行,所以 这个回调函数之内可以调用脚本中任意位置的函数,即使该函数定义在 错误抛出位置之后(函数定义是在 脚本编译期完成的)。

 

四、trigger_error(string errorMsg[,int user_error_type]) 

 该函数用于主动触发一个错误: user_error_type 只能是 E_ALL、E_USER_ERROR、 E_USER_WARNING、 E_USER_NOTICE 或其组合的值。

 

注册 error (包括系统抛出的 Error 和 用户抛出的 Error )的处理函数和消除 error:

<span style="color: #008080;" data-mce-mark="1">set_error_handler</span>(<span style="color: #0000ff;" data-mce-mark="1">callback</span> functionName[,user_error_type]); <span style="color: #008000;" data-mce-mark="1">//</span><span style="color: #008000;" data-mce-mark="1"> 为 trigger_error() 设置一个回调函数来处理错误,包括系统抛出的错误和用户使用 trigger_error() 函数触发的错误。</span>

 

 

可选参数 user_error_type :

如果设定此参数,则 trigger_error 抛出的错误类型符合 在user_error_type 的定义范围才能触发回调函数。

这个值的设置类似于 error_reporting() 函数 。

 

第一个参数(callbeck functionName):

一个函数名,该函数 可以有 5 个参数,其中前 2 个必选,依次是:

trigger_error 抛出的 user_error_type、trigger_error 抛出的 errorMsg、抛出错误的文件的绝对路劲、抛出错误的行号、抛出错误时的上下文环境 (一个数组,包含了trigger_error() 所在作用域内的所有变量、函数、类等数据 )

回调函数的返回值: 如果返回 false ,系统错误处理机制仍然继续抛出该错误,返回 true 或 无返回值 则消除错误。

 

你可以使用 set_error_handler() 来将 PHP 程序 抛出的错误代理给 ErrorException使错误可以类似异常那样显示:

PHP exception handling, error throwing and error callback functions
<span style="color: #0000ff;">function</span> error_handler(<span style="color: #800080;">$errorType</span>, <span style="color: #800080;">$errorMsg</span>, <span style="color: #800080;">$errorFile</span>, <span style="color: #800080;">$errorLine</span><span style="color: #000000;"> ) {
    </span><span style="color: #0000ff;">echo</span> '<div style="color:red;">error_handler is called!</div>'<span style="color: #000000;">;
    </span><span style="color: #0000ff;">throw</span> <span style="color: #0000ff;">new</span> ErrorException(<span style="color: #800080;">$errorMsg</span>, 0, <span style="color: #800080;">$errorType</span>, <span style="color: #800080;">$errorFile</span>, <span style="color: #800080;">$errorLine</span><span style="color: #000000;">);
}
</span><span style="color: #008080;">set_error_handler</span>('error_handler'<span style="color: #000000;">);
</span><span style="color: #008080;">count</span>();
PHP exception handling, error throwing and error callback functions

 

 用户使用 trigger_error()  触发的错误不会被 try-catch 异常捕获语句捕获。

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