为什么 Resharper 认为这个 catch 子句是多余的?
Why does Resharper think that this catch clause is redundant?
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;
}
因为它是默认行为 - 未捕获的异常将更进一步,无需重新抛出它们。
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。
所以,没有区别。
可能是因为您的 catch 块除了重新抛出相同的异常外没有做任何事情:
catch (Exception ex) // Resharper thinks this clause is redundant
{
throw;
}
您可以通过在该 catch 块中添加一些代码来证明这一点。
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;
}
因为它是默认行为 - 未捕获的异常将更进一步,无需重新抛出它们。
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。
所以,没有区别。
可能是因为您的 catch 块除了重新抛出相同的异常外没有做任何事情:
catch (Exception ex) // Resharper thinks this clause is redundant
{
throw;
}
您可以通过在该 catch 块中添加一些代码来证明这一点。