在PHP中嵌套的try catch

时间:2013-10-05 23:55:44

标签: php nested try-catch

考虑:

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。解释是什么?

3 个答案:

答案 0 :(得分:13)

MyException扩展了Exception,因此ExceptonMyException更通用,第一个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;
}