Can I remove empty catch with throw?

Viewed 2083

I'm hoping this is straightforward. I work on a large code-base, the overall quality is good, but occasionally you get some of these:

try
{
   // Calls a .NET remoting method.
}
catch
{
   throw;
}

Note there is no finally logic and the catch does not specify any exceptions or do anything other than what I've provided above. However, I know that catching and re-throwing can alter the call-stack in the exception details. What I'm not sure about is if this behaviour is here specifically because of a .NET remoting call.

Is it safe to remove this try-catch? So far as I can see, it is, but I thought I'd double check for any odd behaviour first.

4 Answers

While, in most cases, it probably is redundant/unnecessary code, try { .. } catch { throw; } can suppress compiler optimizations and JIT method inlining. This is mostly seen in call-stack traces.

Thus, there "could" be a side-effect that is relied on elsewhere.

Arguably, the 'error' would be in reliance on this implementation detail, especially without explicit documentation about such expected behavior.. and especially since such is not a guarantee.

See Release IS NOT Debug: 64bit Optimizations and C# Method Inlining in Release Build Call Stacks which predated even this old question.

While the code seems redundant, the try-catch code won't be eliminated during compilation either.

Related