【问题标题】:Rethrow php exception into higher level catch block将php异常重新抛出到更高级别的catch块中
【发布时间】:2011-09-16 15:43:21
【问题描述】:

我正在尝试将异常从特定的 catch 块传递到更通用的 catch 块。但是,它似乎不起作用。尝试以下操作时出现 500 服务器错误。这甚至可能吗?

我知道有一些简单的解决方法,但是说“嘿,我不想处理这个错误,让我们让更通用的异常处理程序来处理它!”这不是很正常吗?

try {
   //some soap stuff
}

catch (SoapFault $sf) {
    throw new Exception('Soap Fault');
}

catch (Exception $e) {
     echo $e->getMessage();
}

【问题讨论】:

  • 不行,使用异常来处理流控是不正常的。
  • 也许人们需要查看投票规则。如果某人正在做的是一个坏主意,那么请解释原因。如果这是一个格式不正确的问题,请投反对票 - meta.stackexchange.com/questions/33286/…

标签: php exception-handling try-catch


【解决方案1】:

从技术上讲,这就是您要寻找的:

try {
    try {
       //some soap stuff
    }    
    catch (SoapFault $sf) {
        throw new Exception('Soap Fault');
    }
}
catch (Exception $e) {
     echo $e->getMessage();
}

但是我同意不应将异常用于流控制。更好的方法是这样的:

function show_error($message) {
    echo "Error: $message\n";
}

try {
   //some soap stuff
}    
catch (SoapFault $sf) {
    show_error('Soap Fault');
}
catch (Exception $e) {
    show_error($e->getMessage());
}

【讨论】:

  • 在某些情况下,您需要重新抛出异常。例如,如果您有一个类构造函数并在其中捕获异常(例如,将错误记录到特殊文件中),那么您将不得不重新抛出异常以通知构造调用者该错误。
猜你喜欢
  • 2014-06-19
  • 1970-01-01
  • 2012-02-20
  • 1970-01-01
  • 1970-01-01
  • 2012-09-14
  • 2016-12-11
  • 1970-01-01
相关资源
最近更新 更多