2010-05-09 184 views
0

我不知道在PHP中拋出的異常將終止在PHP腳本?異常拋出終止腳本?

因爲當我保存已經在教義中創建的條目,它會引發異常。

我捕捉到異常並忽略它(以便用戶不會看到它),但腳本似乎被終止。

有沒有辦法捕捉異常並保持腳本活着?

感謝

+3

是的,我在最後一個問題中展示瞭如何做到這一點。 http://stackoverflow.com/questions/2796863/unknown-exception-error-in-php/2796903#2796903 – 2010-05-09 07:31:11

+1

是的異常將終止腳本。您可能會從catch塊中拋出另一個異常,或者另一個錯誤可能導致腳本終止。調試我的朋友! :) – Andreas 2010-05-09 07:38:25

回答

2

你需要用函數調用(一個或多個)可以在一個try...catch塊拋出異常。

class EvilException extends Exception {} 
class BadException extends Exception {} 

function someMethodThatMayThrowException() { 
    ... 
    ... 
    throw new EvilException("I am an evil exception. HAHAHAHA"); 
} 
try { 

someMethodThatMayThrowException(); 

} catch(BadException $e) { 
    //deal with BadException here... 
} catch(EvilException $e) { 
    //deal with EvilException here... 
    throw new Exception("will be caught in next catch block"); 
} catch(Exception $e) { 
    echo $e->getMessage(); //echoes the string: "will be caught in next catch block" 
} 

如果發現異常,腳本將不會終止。如果拋出的異常沒有跳轉到catch塊,上述情況就會發生。

+1

+1您還可以在'catch'塊中再次拋出異常以傳遞它。 – 2010-05-09 07:48:00