I'm not familiar with java and I've been recently looking at some code written by some colleagues that's baffling me. Here's the gist of it:
public response newStuff(//random data inside) { try { response or = //gives it a value log.info(or.toString()); return or; } catch ( Exception e) { e.printStackTrace(); } finally { return null; } }
Is there really any point in adding a finally block here? Couldn't I just add the return null inside the catch block, which would execute the same behavior, or am I wrong?
In general both block should declare an exit. If in try you have return you should have also it in catch, in your case the second return was replaced with throw.
Yes, we can write a return statement of the method in catch and finally block.
When try and finally block both return value, method will ultimately return value returned by finally block irrespective of value returned by try block.
Yes, the finally block will be executed even after a return statement in a method. The finally block will always execute even an exception occurred or not in Java. If we call the System.
Is there really any point in adding a finally block here?
The answer to this is a resounding "no": putting a return
statement in the finally
block is a very bad idea.
I just add the return null inside the catch block, which would execute the same behavior, or am I wrong?
It wouldn't match the original behavior, but that's a good thing, because it would fix it. Rather than returning null
unconditionally the way the original code does, the code with the return
inside the catch
block would return null
only on errors. In other words, the value returned in the try
branch would be returned to the caller unless there is an exception.
Moreover, if you add return null
after the catch
block, you would see the correct effect of returning null
on exception. I would go even further, and put a single return
in the method, like this:
response or = null; try { or = //gives it a value log.info(or.toString()); } catch ( Exception e) { e.printStackTrace(); } return or;
Actually, no. Finally is (nearly) always run, no matter what the result in the try-catch block; so this block always returns null
. Here, look at this example:
public class Finally { /** * @param args */ public static void main(String[] args) { System.out.println(finallyTester(true)); System.out.println(finallyTester(false)); } public static String finallyTester(boolean succeed) { try { if(succeed) { return "a"; } else { throw new Exception("b"); } } catch(Exception e) { return "b"; } finally { return "c"; } } }
It will print "c" both times.
The above mentioned exception to the rule would be if the thread itself is interrupted; e.g. by System.exit()
. This is however a rare thing to happen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With