网站首页 文章专栏 PHP异常捕获
捕获异常是基于PHP自带的基类Exception,常用try、throw、catch三个关键字来处理
1、try:
用于可能发生异常的代码块。这里用来写逻辑代码
2、throw:
规定如何触发(trigger)异常,用于抛出异常。每一个throw必须对应至少一个catch。这个就是声明,这里遇到了异常报错,使用Exception对象来抛出异常
3、catch:
捕获异常,并创建包含异常信息的对象。
PS:php的异常必须遇到throw关键字才能捕获到。
eg:
try { //一堆逻辑处理后,发现有问题,就用throw 中断 并抛出异常 throw new Exception("Some error message", 2);//抛出异常,设置异常代号为2 } catch(Exception $e) { echo "Exception:file:".$e->getFile().",message:" . $e->getMessage().",code:".$e->getCode()."line:".$e->getLine(); //Exception:file:D:\phpstudy_pro\WWW\要整理的.php,message:Some error message,code:2line:43 }
也可以自己定义异常:
class customException extends Exception { public function errorMessage() { //error message $errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile() .': <b>'.$this->getMessage().'</b>'; return $errorMsg; } } try{ throw new customException("这里是异常,快点来处理。"); } catch(customException $ex){ #some codes echo $ex->errorMessage(); //Error on line 33 in D:\phpstudy_pro\WWW\要整理的.php: 这里是异常,快点来处理。 }
转载请注明出处