考虑:
try{
class MyException extends Exception{}
try{
throw new MyException;
}
catch(Exception $e){
echo "1:";
throw $e;
}
catch(MyException $e){
echo "2:";
throw $e;
}
}
catch(Exception $e){
echo get_class($e);
}
我对此尝试和捕捉感到困惑。由于第二个2:MyException
,我期待try throw MyException
结果。但实际结果是1:MyException
。解释是什么?
答案 0 :(得分:13)
MyException
扩展了Exception
,因此Excepton
比MyException
更通用,第一个catch
块会抓住它。如果你想抓住MyException
,你需要违反catch
块的顺序:
class MyException extends Exception{}
try{
try{
throw new MyException;
}catch(MyException $e){
echo "2:";
throw $e;
}catch(Exception $e){
echo "1:";
throw $e;
}
}catch(Exception $e){
echo get_class($e);
}
答案 1 :(得分:5)
第一个catch-block捕获了'Exception'类的所有内容。由于MyException扩展了Exception类,因此MyException会在第一个catch块中被捕获。
答案 2 :(得分:0)
如果检查类名并相应地处理它会更好。
class MyException extends Exception {}
try {
throw new MyException;
}
catch (Exception $ex){
switch (get_class ($ex)) {
case "MyException" :
// Do whatever you want to do for MyException
break;
default:
// Do whatever you want to do for Exception
break;
}
throw $ex;
}