您好,欢迎访问一九零五行业门户网

php异常处理 - 蜀都小一

使用try{thow}catch(){}异常处理结构,可以有效的控制多行可能发生异常的代码,基本模型如下:
phptry{throw new exception(错误信息;) //抛出一个错误} catch(exception $e) //捕获错误信息,exception是一个内置的错误处理类{echo $e->getmessage(); //输出错误信息echo $e->getcode(); //返回异常代码echo $e->getfile(); //返回发生异常的文件echo $e->getline(); //返回发生异常的行号}?>
exception原形:
phpclass exception{ protected $message = 'unknown exception'; // 异常信息 private $string; // __tostring cache protected $code = 0; // 用户自定义异常代码 protected $file; // 发生异常的文件名 protected $line; // 发生异常的代码行号 private $trace; // backtrace private $previous; // previous exception if nested exception public function __construct($message = null, $code = 0, exception $previous = null); final private function __clone(); // inhibits cloning of exceptions. final public function getmessage(); // 返回异常信息 final public function getcode(); // 返回异常代码 final public function getfile(); // 返回发生异常的文件名 final public function getline(); // 返回发生异常的代码行号 final public function gettrace(); // backtrace() 数组 final public function getprevious(); // 之前的 exception final public function gettraceasstring(); // 已格成化成字符串的 gettrace() 信息 public function __tostring(); // 可输出的字符串}?>
同时,一个try也可以关联多个catch块,可以自定义类继承exception类来实现
phpclass myexception1 extends exception{} //根据需要自定义class myexception2 extends exception{}class myexception3 extends exception{}try{switch(1){case 1:throw new myexception1();case 2:throw new myexception2();case 3:throw new myexception3(); //当找不到对应的catch代码块时,将会抛到exception处理,因为myexception3继承了exception}}catch(myexception1 $e){echo 自定义错误1;}catch(myexception2 $e){echo 自定义错误2;}catch(exception $e){echo 原始异常类; }?>
其它类似信息

推荐信息