Heim  >  Artikel  >  Backend-Entwicklung  >  php异常、错误处理机制

php异常、错误处理机制

WBOY
WBOYOriginal
2016-08-08 09:19:30777Durchsuche
 

php异常、错误处理机制


在实际开发中,错误及异常捕捉仅仅靠try{}catch()是远远不够的。 所以引用以下几中函数。

我们先来说异常:

首先要明白异常跟错误是不一样的,异常是出现正常逻辑之外的情况,而错误是指运行时出错了,比如,使用了一个未定义的变量等,异常需要抛出(throw)才能被捕捉到,而错误会导致程序执行终止

1、通常处理异常的方式是使用try{}catch{}去捕捉有throw抛出的异常

[php] view plaincopy

  1. try{  
  2.     throw new Exception("kkkkkkkkkkkkkkkk");  
  3. }  
  4. catch(Exception $e){  
  5.     echo $e->getMessage(),"",$e->getTraceAsString();  
  6. }  

2、通过set_exception_handler函数设置异常处理函数,在这种情况下,即使没有try{}catch{},throw抛出的异常也能由set_exception_handler设置的函数自动捕捉

[php] view plaincopy

  1. set_exception_handler('exceptionHandler');  
  2. throw new Exception("kkkkkkkkkkkkkkkk");  
  3. function exceptionHandler(Exception $exception){  
  4.       
  5.     echo $exception->getMessage();  
  6. }  

接下来讨论错误:

通常程序出错了,php会输出出错的信息来帮助调试,但是这个信息的输出是可以通过函数error_reporting()来控制的。在php中错误是分等级和种类的,下面是所有错误种类的说明:
E_ALL - 所有的错误和警告(不包括 E_STRICT)
E_ERROR - 致命性的运行时错误
E_WARNING - 运行时警告(非致命性错误)
E_PARSE - 编译时解析错误
E_NOTICE - 运行时提醒(这些经常是你代码中的bug引起的,也可能是有意的行为造成的。)
E_STRICT - 编码标准化警告,允许PHP建议如何修改代码以确保最佳的互操作性向前兼容性。
E_CORE_ERROR - PHP启动时初始化过程中的致命错误
E_CORE_WARNING - PHP启动时初始化过程中的警告(非致命性错)
E_COMPILE_ERROR - 编译时致命性错
E_COMPILE_WARNING - 编译时警告(非致命性错)
E_USER_ERROR - 用户自定义的错误消息
E_USER_WARNING - 用户自定义的警告消息
E_USER_NOTICE - 用户自定义的提醒消息

如果设置了error_reporting(E_NOTICE),那么程序只会输出E_NOTICE等级的信息,一般我们使用的时候只需要设置error_reporting(E_ALL&!E_WARNING)就行了

上面我们看到有一种错误叫用户自定义的错误消息,这是什么呢?我们先看一个例子

[php] view plaincopy

  1. set_error_handler('errorHandler');  
  2. trigger_error("aaaaaaassssssssssss",E_USER_ERROR);  
  3. function errorHandler($errno,$errstr){  
  4. "white-space:pre">  if($errno==E_USER_ERROR){  
  5. "white-space:pre">      echo "innnnnnnni:",$errstr;  
  6. "white-space:pre">  }  
  7. "white-space:pre">    
  8. }  
输出结果:

[php] view plaincopy

  1. innnnnnnni:aaaaaaassssssssssss  

trigger_error()就是用来抛出用户自定义错误消息的函数,通过这个我们能抛出自定义的一些消息被当作错误来处理,比如严重的逻辑问题

上面的程序我们看到,当程序出错时,除了让Php默认输出出错信息外,我们还能设置自己的错误处理函数,设置的方法就是set_error_handler(),下面来看个例子

[php] view plaincopy

  1. set_error_handler('errorHandler');  
  2. echo "dddddddddddd";  
  3. echo $cc;//$cc没有定义,echo会出错  
  4. function errorHandler($errno,$errstr){  
  5.     if($errno==E_NOTICE){  
  6.         echo "innnnnnnni:",$errstr;  
  7.     }  
  8. }  

输出结果:

dddddddddddd
innnnnnnni:Undefined variable: cc

以上就介绍了php异常、错误处理机制,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Vorheriger Artikel:PHP实现下载文件功能Nächster Artikel:php ci开发基础应用