c# - 为什么 Resharper 认为这个 catch 子句是多余的?

标签 c# resharper

<分区>

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

最佳答案

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

C# reference :

When an exception is thrown, the common language runtime (CLR) looks for the catch statement that handles this exception. If the currently executing method does not contain such a catch block, the CLR looks at the method that called the current method, and so on up the call stack.

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

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

所以,没有区别。

关于c# - 为什么 Resharper 认为这个 catch 子句是多余的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38468980/

相关文章:

c# - 绑定(bind)不起作用,因为值未定义

c# - 使用 Roslyn 创建部分类 - 一个在运行时编译的类

c# - 将 C# 8 可空引用类型标记为 "this can' t 为空”

visual-studio-2005 - 如何最好地处理 Visual Studio 中的巨大源代码文件

c# - 将 BindList<Classname> 转换为 BindingList<Interface>

c# - 关键字 'add' 附近的语法不正确

git - 在源代码管理中我应该保留哪些 ReSharper 文件以及应该忽略哪些文件?

visual-studio - ReSharper 和 NUNIT 的 NUnit 运行程序编译失败错误

resharper - 我可以让 R# 智能感知选择第一个列表项吗?

resharper - 使用 ReSharper 的项目忽略代码检查设置的正确方法是什么?