Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Resharper think that this catch clause is redundant? [duplicate]

Tags:

c#

resharper

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;
}
like image 957
AngryHacker Avatar asked Jul 19 '16 21:07

AngryHacker


2 Answers

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.

like image 76
lorond Avatar answered Sep 20 '22 19:09

lorond


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.

like image 34
Jeroen van Langen Avatar answered Sep 19 '22 19:09

Jeroen van Langen