Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I remove empty catch with throw?

Tags:

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.

like image 575
Adam Houldsworth Avatar asked Jun 29 '11 08:06

Adam Houldsworth


People also ask

What happens if catch block is empty?

It will generate an exception that is caught by the catch block. The catch block catches and handles the exception. If the catch block is empty then we will have no idea what went wrong within our code.

Can we use throw without catch?

4. throws: The throws keyword is used for exception handling without try & catch block. It specifies the exceptions that a method can throw to the caller and does not handle itself.

What happens if you throw in a catch?

It's passing the exception up to the next handler. If there is a try... catch block around the method call in which the exception is caught and thrown, it will be picked up and processed by that handler instead.


Video Answer


1 Answers

Rethrowing as you've shown it shouldn't change the call stack, unless there's something very special about remoting exceptions. (I know there are some special aspects, but I don't think they come into play here.) This is the kind of thing which does lose information:

catch(Exception e) {     throw e; // Not throw; } 

My guess is that some developer has included this just so they can put a breakpoint on the throw line. I would get rid of it.

like image 150
Jon Skeet Avatar answered Nov 12 '22 16:11

Jon Skeet