PHP的基本异常类,它提供一个不带参数的默认构造函数,一个带有两个可选参数的重载构造函数,还包括6个方法。
1.默认构造函数
throw new Exception();
getCode()。返回传递给构造函数的错误代码
getFile()。返回抛出异常的文件名
getLine()。返回抛出异常的行号
getMessage()。返回传递给构造函数的消息
getPrevious()。返回前一个异常(假设已经通过异常构造函数传入)
throw new Exception("Something bad just happened",4,$e);
getTrace()。返回一个数组,其中包括出现错误的上下文的相关信息。确切的讲,该数组包括文件名,行号,函数名和函数参数
getTraceAsString()。返回与getTrace()完全相同的信息,只是返回的信息是一个字符串不是数组。
注:虽然可以扩展异常基类,但不能覆盖之前的任何一个方法,因为他们都声明为final
try{
$fh = fopen("con.txt","r");
if(!$fh){
throw new Exception("Could not open the file!");
}
}catch(Exception $e){
echo "Error (File: ".$e->getFile().", line ".$e->getLine(). "):".$e->getMessage();
}
2.扩展异常类
class MyException extemds Exception{
function __construct($language,$errorcode){
$this->language = $language;
$this->errorcode = $errorcode;
}
function getMessageMap(){
$errors = file("errors/".$this->language.".txt");
foreach($errors as $error){
list($key,$value) = explode(",",$error,2);
$errorArray[$key] = $value;
}
return $errorArray[$this->errorcode];
}
}
try{
throw new MyException("english",4);
}catch(MyException $e){
echo $e->getMessageMap();
}