【问题标题】:Why does Resharper think that this catch clause is redundant? [duplicate]为什么 Resharper 认为这个 catch 子句是多余的? [复制]
【发布时间】:2016-11-22 23:10:06
【问题描述】:

Resharper 认为最后一个 catch 子句是多余的。为什么?

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUrl);

try
{
    var response = (HttpWebResponse) request.GetResponse();
    using (var streamReader = new StreamReader(response.GetResponseStream()))
    {
        var jsonResult = streamReader.ReadToEnd();
    }
}
catch (WebException e)
{
    Exception newEx;
    if (e.Response != null)
    {
        using (var sr = new StreamReader(e.Response.GetResponseStream()))
        {
            newEx = new Exception(sr.ReadToEnd(), e);
        }
    }
    else
    {
        newEx = new Exception(e.Message, e);                    
    }

    throw newEx;
}
catch (Exception ex)  // Resharper thinks this clause is redundant
{
    throw;
}

【问题讨论】:

  • 你只是在捕捉并重新抛出前任。你不需要那个 catch {} 子句,没有它也会有同样的效果。

标签: c# resharper


【解决方案1】:

因为它是一种默认行为 - 未捕获的异常将更进一步,无需重新抛出它们。

C# reference:

当引发异常时,公共语言运行时 (CLR) 会查找处理此异常的 catch 语句。如果当前执行的方法不包含这样的 catch 块,则 CLR 会查看调用当前方法的方法,并在调用堆栈中以此类推。

在您的特定情况下,如果您不重新抛出异常,那么WebException clr 将继续展开堆栈以寻找下一个 try-catch。

如果您重新抛出该异常,clr 也会继续展开堆栈以寻找下一个 try-catch。

所以,没有区别。

【讨论】:

  • 是的,无论如何它都会抛出,如果你只是抛出它,那就是多余的捕获:P
【解决方案2】:

可能是因为你的 catch 块除了重新抛出相同的异常之外什么也没做:

catch (Exception ex)  // Resharper thinks this clause is redundant
{
    throw;
}

您可以通过在该 catch 块中添加一些代码来证明这一点。

【讨论】:

    猜你喜欢
    • 2010-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-23
    • 2010-10-14
    • 2019-06-18
    相关资源
    最近更新 更多