非常处置惩罚归类于毛病处置惩罚,PHP从5.1.0最先增加了Exception非常处置惩罚类。
一、非常处置惩罚
PHP非常处置惩罚与Java类似,都运用try、throw、catch语句,发作非常时代码。假如非常没有被捕捉,而且又运用set_exception_handler()函数作响应的处置惩罚的话,那末将发作一个严峻的毛病(致命毛病),而且输出 "Uncaught Exception" (未捕捉非常)的毛病音讯。
1、try:
用于能够发作非常的代码块。
2、throw:
划定怎样触发(trigger)非常,用于抛出非常。每个throw必需对应最少一个catch。
3、catch:
捕捉非常,并建立包括非常信息的对象。
申明:权且以为php的非常必需throw才捕捉到。
基础构造:
try{ #some codes throw new Exception("message"[,code[,...]]); } catch(Exception $ex){ #some codes }
二、PHP 非常基类Exception
类择要:
Exception { /* 属性 */ protected string $message ; protected int $code ; protected string $file ; protected int $line ; /* 要领 */ public __construct ([ string $message = "" [, int $code = 0 [, Exception $previous = NULL ]]] ) final public string getMessage ( void ) final public Exception getPrevious ( void ) //猎取非常链中前一个非常 final public int getCode ( void ) final public string getFile ( void ) final public int getLine ( void ) final public array getTrace ( void ) //猎取非常追踪信息 final public string getTraceAsString ( void ) //字符串体式格局返回非常追踪信息 public string __toString ( void ) final private void __clone ( void ) }
示例:
<?php try { throw new Exception("Some error message", 30);//抛出非常,设置非常代号为30 } catch(Exception $e) { echo "Exception:file:".$e->getFile().",message:" . $e->getMessage().",code:".$e->getCode()."line:".$e->getLine(); } ?>
三、自定义非常类
实例:
class customException extends Exception { public function errorMessage() { //error message $errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile() .': <b>'.$this->getMessage().'</b> is not a valid E-Mail address'; return $errorMsg; } }
抛出与捕捉该非常:
try{ throw new customException("这是自定义非常。"); } catch(customException $ex){ #some codes }
四、多catch捕捉非常
当一个try语句中能够抛出差别的非常时,对应的可有多个catch块捕捉差别范例非常。同java中的一些注重点:
1、大非常catch放背面。由于抛出非常时按递次推断先满足哪一个catch,一次仅实行一个catch。
2、实行一次try,最多实行一个catch(发作非常时),即若前面某个catch满足实行,则背面的catch不再斟酌。
引荐教程:PHP视频教程
以上就是PHP项目非常类该怎样设想的细致内容,更多请关注ki4网别的相干文章!