Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad practice to return from within a try catch finally block?

People also ask

Is it good practice to return from TRY block?

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.

Is nested try catch bad practice?

I actually don't think there's anything inherently wrong about nested Try / Catch blocks, except that they can be difficult to navigate and are likely a sign that you could do some refactoring (the inner Try / Catch into its own method, for example).

Can you return in a finally block?

Yes you can write the return statement in a finally block and it will override the other return value. The output is always 2, as we are returning 2 from the finally block.

What happens if we place return statement in try catch block?

Upon the completion of finally block execution, control goes back to the return statement in the try block and returns “returning from try block”. If finally block has a return statement, then the return statements from try/catch blocks will be overridden.


No, it's not a bad practice. Putting return where it makes sense improves readability and maintainability and makes your code simpler to understand. You shouldn't care as finally block will get executed if a return statement is encountered.


The finally will be executed no matter what, so it doesn't matter.


Personally, I would avoid this kind of coding as I don't feel like seeing return statements before finally statements.

My mind is simple and it process things rather linearly. Therefore when I walk through the code for dry running, I will have tendency to think that once I can reach the return statement, everything follow doesn't matter which obviously is pretty wrong in this case (not that it would affect the return statement but what the side effects could be).

Thus, I would arrange the code so that the return statement always appear after the finally statements.


This may answer your question

What really happens in a try { return x; } finally { x = null; } statement?

From reading that question it sounds like you can have another try catch structure in the finally statement if you think it might throw an exception. The compiler will figure out when to return the value.

That said, it might be better to restructure your code anyway just so it doesn't confuse you later on or someone else who may be unaware of this as well.


Functionally there is no difference.

However there is one reason for not doing this. Longer methods with several exit points are often more difficult to read and analyze. But that objection has more to do with return statements than catch and finally blocks.