9

Resharper thinks the last catch clause is redundant. Why?

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;
}
AngryHacker
  • 59,598
  • 102
  • 325
  • 594
  • 3
    You're just catching and re-throwing ex. You don't need that catch {} clause, it will have the same effect without it. – Jon Jul 19 '16 at 21:42
  • It has already been explained why this code is redundant. Perhaps you're unsure as to what exceptions might be thrown by the code in your try block, it might be include some library that you're not familiar with. Perhaps your exception settings are set to skip over entire categories of exceptions. In that case it can be very useful to have a breakpoint set inside the redundant catch block while you're debugging so you can inspect anything that goes through there. Make sure you remove it before committing your code though – user1007074 May 11 '22 at 16:07

2 Answers2

10

Because it is a default behavior - not caught exceptions will go further without need to rethrow them.

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.

In your particular case if you will not rethrow exceptions, other then WebException clr will continue to unwind stack looking for next try-catch.

If you rethrow that exceptions, clr will continue to unwind stack looking for next try-catch too.

So, no difference.

lorond
  • 3,856
  • 2
  • 37
  • 52
6

Probably because your catch block isn't doing anything except rethrowing the same exception:

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

You could proof it by adding some code in that catch block.

Jeroen van Langen
  • 21,446
  • 3
  • 42
  • 57