【问题标题】:Can results from a catch block be passed to methods inside the try block?可以将 catch 块的结果传递给 try 块中的方法吗?
【发布时间】:2012-07-17 10:29:43
【问题描述】:

我的程序中有以下代码:

HttpWebResponse response = null;
try
{
    response = (HttpWebResponse)request.GetResponse();
    if (response == null)
        return false;
    aDoc.Load(response.GetResponseStream()); //Load the response into another object
}
catch (WebException e)
{
    //404's are caught and are saved as the response.
    //The reason being that 404's from this particular
    // website still provide relevant information that needs
    // extracting.
    response = (HttpWebResponse)e.Response;
}
finally
{
    response.Close();
}

我的问题是:如果捕获到 WebException,是否会将来自 response = (HttpWebResponse)e.Response; 的响应传递给 aDoc.Load() 方法?

顺便说一句,在将更多代码移入 try-catch 块之前,我有以下代码。我认为添加 finallyClose() 会更安全,但我仍然想知道我是否应该首先更改任何内容。

HttpWebResponse response = null;
try
{
    response = (HttpWebResponse)request.GetResponse();
}
catch (WebException e)
{
    response = (HttpWebResponse)e.Response;
}

if (response == null)
    return false;
aDoc.Load(response.GetResponseStream());
response.Close();

【问题讨论】:

    标签: c# error-handling scope try-catch httpwebresponse


    【解决方案1】:

    没有。您需要像在第二个示例中所做的那样隔离正确的代码块。

    当然可以嵌套:

    HttpWebResponse response = null;
    
    try {
        try {
            response = (HttpWebResponse)request.GetResponse();
        } catch (WebException e) {
            response = (HttpWebResponse)e.Response;
        }
    
        if (response == null) return false;
    
        aDoc.Load(response.GetResponseStream());
    } finally {
        if (response != null) response.Close();
    }
    

    【讨论】:

    • 这肯定对我有用:)。我对多个巢穴有一种奇怪的恐惧,我责怪我没有看到这个解决方案。既然您评论了我的第二个代码 sn-p,您能否说该代码是否比您提供的代码“不安全”?或者,没有明显的区别?
    • 在第二次 sn-p 中,如果 aDoc.Load() 抛出异常,您将永远无法到达 response.Close()。但是,响应是一次性的,因此它最终可能会被清除。
    • 啊,我明白了。感谢您的回复和您的回答。
    【解决方案2】:

    不,

    如果抛出了WebException,则它已离开try 块,并且不会执行try 块中的其他代码,只会执行finally 块中的代码。

    【讨论】:

    • 还不能+1,所以我会添加评论,感谢您的回复:D
    【解决方案3】:

    答案是肯定的和否定的 - 因为将响应传递给aDoc.Load() 的代码是最后一条语句,所以异常只能发生在该行之上或之上。

    假设aDoc.Load()从不抛出WebException,那么答案是否定的

    如果 aDoc.Load() 抛出 WebException 则异常可能来自该方法 - 所以从技术上讲,aDoc.Load() 可能已通过 GetResponse() 方法的结果,异常可能已在 aDoc.Load() 中引发 - 取决于 @ 987654327@ 实现虽然

    异常会停止代码执行,因此一旦抛出异常,下一段要执行的代码就是 catch 块中的代码(或者如果不存在,则在堆栈中更靠前的任何 catch 块)然后运行finally

    我的假设是 aDoc.Load() 不是任何类型的 Web 方法(并且可能是您自己的类),因此您最好了解这是否会引发 WebException,但答案可能是“否”

    【讨论】:

    • 您的假设是正确的。 Load() 方法是帮助解析网页的 HtmlAgilityPack 的一部分。此特定方法不访问网络。即使我没有考虑抛出异常的那一行,它也让我对异常期间发生的事情有了更深入的了解。所以,谢谢你的回复:)
    • 我已经澄清了一点答案,因为我认为它缺少一些细节
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-16
    • 2013-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多