里面的PHP异常catch:如何处理?

时间:2014-08-26 12:48:06

标签: php exception-handling

假设在try...catch块中包含PHP代码。假设在catch内你想做一些可能会失败的事情(即发送电子邮件)并抛出新的异常。

try {
    // something bad happens
    throw new Exception('Exception 1');
}
catch(Exception $e) {
    // something bad happens also here
    throw new Exception('Exception 2');
}

处理catch阻止内的异常的正确(最佳)方式是什么?

3 个答案:

答案 0 :(得分:1)

你不应该在catch中扔任何东西。如果你这样做,那么你可以省略try-catch的这个内层并在try-catch的外层捕获异常并在那里处理那个异常。

例如:

try {
    function(){
        try {
            function(){
                try {
                    function (){}
                } catch {
                    throw new Exception("newInner");
                }
            }
        } catch {
            throw new Exception("new");
        }
    }
} catch (Exception $e) {
    echo $e;
}

可以替换为

try {
    function(){
        function(){
            function (){
                throw new Exception("newInner");
            }
        }
    }
} catch (Exception $e) {
    echo $e;
}

答案 1 :(得分:1)

基于this answer,嵌套try / catch块似乎是完全有效的,如下所示:

try {
   // Dangerous operation
} catch (Exception $e) {
   try {
      // Send notification email of failure
   } catch (Exception $e) {
      // Ouch, email failed too
   }
}

答案 2 :(得分:0)

您有两种可能的方式:

  1. 退出程序(如果程序很严重)并将其写入日志文件并通知用户。
  2. 如果错误是特定于您当前的类/函数, 你在catch块内抛出另一个错误。
相关问题