• Post Reply Bookmark Topic Watch Topic
  • New Topic

java try catch block  RSS feed

 
Sanjiv Saha
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is it a best practice to return from try block or place return statement after try-catch when we intend to return a value from a method(* Catch block is being also used to rethrow the exception)?? Pleas suggest..
 
Campbell Ritchie
Marshal
Posts: 56593
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please explain more details. Why would you want to return something and re-throw the Exception? The correct answer depends on the situation.

I am pretty sure, however, you should not return things from the finally.
 
Mike. J. Thompson
Bartender
Posts: 689
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Personally I always put the return in the try block in that situation. The return is part of the non-exceptional case so it is least surprising for it to appear next to the code it relates to.

Also if you place the return outside of the try block then you will need to declare the variable it is returning outside of the try block. Presumably the code in the try block is involved in calculating the returned value, so this means you will need to separate the declaration from the initialisation for at least one variable. I don't like doing this with local variables unless I have to.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!