将php异常返回到更高级别的catch块 [英] Rethrow php exception into higher level catch block

查看:149
本文介绍了将php异常返回到更高级别的catch块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将一个异常从一个特定的catch块传递给一个更一般的catch块。但是它似乎没有工作。当我尝试以下操作时,我收到一个500服务器错误。这是可能的吗?

I am trying to pass an exception from a specific catch block to a more general catch block. However it does not appear to be working. I get a 500 server error when I try the following. Is this even possible?

我意识到有很容易的解决方法,但不正常的说,嘿,我不想处理这个错误,让我们有更一般的异常处理程序来处理它!

I realize that there are easy workarounds, but isn't it normal to say, "Hey I don't feel like dealing with this error, let's have the more general exception handler take care of it!"

try {
   //some soap stuff
}

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

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


推荐答案

从技术上讲,重新寻找:

Technically this is what you're looking for:

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

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

however I agree that exceptions shouldn't be used for flow control. A better way would be like this:

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

这篇关于将php异常返回到更高级别的catch块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆