8

Consider:

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);
}

I am confused with this try and catch. I am expecting a 2:MyException result because of the second try throw MyException. But the actual result is 1:MyException. What is the explanation?

4

3 回答 3

20

MyExceptionextends Exception,所以Exception比 更通用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);
}
于 2013-10-06T00:02:07.207 回答
6

第一个 catch 块捕获 'Exception' 类的所有内容。由于您的 MyException 扩展了 Exception 类,因此 MyException 在第一个 catch 块中被捕获。

于 2013-10-05T23:59:03.703 回答
1

如果您检查类名并相应地处理它会更好。

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;
}
于 2014-08-27T01:35:15.150 回答