PHP – PHP5中的异常
PHP5支持Exception模型,例如C++/C#和Java。
捕获异常的语法:
try {
//可以启动异常的代码
//[...]
//手动异常抛出
throw new Exception(“thrown exception”);
//不执行!(抛出命令被捕获在下面
print “not printed!”;
}
catch(Exception $e) { print $e->getMessage();}
this code prints : “thrown exception”.
It’s possibile to throw an exception inside a catch construct. The new exception will be caught in the external try-catch block.
try {
try{
throw new Exception(“internal exception”);
}
catch (Exception $e) { throw new Exception($e->getMessage()); }
print “not printed!”;
}
catch(Exception $e) { print $e->getMessage(); }这段代码显示:“内部异常”
“Exception”内置类的结构和继承
class Exception
{
protected $message = ‘Unknown exception’; //异常消息
protected $code = 0; //用户定义的异常代码
protected $file; //异常的源文件名
protected $line; //异常源行
function __construct($message = null, $code = 0);
final function getMessage(); //例外信息
final function getCode(); //例外代码
final function getFile(); //源文件名
final function getLine(); //源行
final function getTrace(); //backtrace()的数组
final function getTraceAsString(); //格式化的跟踪字符串
/* Overrideable */
function __toString(); //用于显示的格式化字符串
}如果是扩展,请记住在扩展类构造函数
parent:中调用超类构造函数:__construct()
多个catch构造
允许在try构造之后指定多个catch。
如果异常与参数不匹配,它将被捕获到下一个catch块。
注意:Exception对象也与其子类的对象匹配。注意顺序!
class MyException extends Exception {/* …*/ }
try{
throw new MyException(“”);
}
catch (MyException $e) {//打印“MyException”;
}
catch (Exception $e) { //从未执行
print “Exception”;
}
And …
try{
throw new MyException(“”);
}
catch (Exception2 $e) { print “Exception”; }
catch (Exception $e) { //打印“Exception”;
}
catch (MyException $e) { print “MyException”; }