伪代码如下:
try{
do somthing
if somting error
throw exception("Somting bad happened")
}catch(exception){
ouput the exception message
}
也支持创建多个处理器块来解决多个错误。为此,你可以使用各个预定义处理器,或者扩展某个预定义处理器,
创建你自己的处理器。PHP目前只提供一个简单的处理器Exception。
下面是基于多个处理块的伪代码:
try{
do IO somting
if IO somting error
throw IOexception("IO ERROR")
if Numberexception Error
throw Numberexception
}catch(IOexception){
ouput the IOexception message
}catch(Numberexception){
output the Numberexception
}
真是代码:
try{
if(!@mysql_connect('localhost','root','password')){
throw new Exception("数据库连接失败");
}else{
#OK
}
}catch(Exception $e){
echo "someError:".$e->getMessage().'发生在第'.$e->getLine().'行';
}
//下面是多处理器块的演示
try{
if(!@mysql_connect('localhost','root','password')){
throw new Exception("数据库连接失败");
}else{
#OK
if(!mysql_select_db('database'))
throw new DbException("数据库不存在");
}
}catch(Exception $e){
echo "someError:".$e->getMessage().'发生在第'.$e->getLine().'行';
}catch(DbException $e){
echo "错误发生在:".$e->getLine();
}
//DbException是Exception的扩展类。这里没有写出,因为功能与Exception一样