• Post Reply Bookmark Topic Watch Topic
  • New Topic

Best Practice where to write return statement?  RSS feed

 
Amandeep Singh
Ranch Hand
Posts: 853
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator




what is the best practice, should i use return statement inside try ?






or
what is the best practice, should i use return statement after catch ?

Please don't consider finally block in my example.
 
Piyush Porwal
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From what I have read in the books, a try..catch block should consists of minimal code which can throw an exception. So if return is not expected to throw any exception, it should be outside of the try block. If you are doing something funky in the return like as simple as

then move it out only when you do not expect Dog constructor to throw an exception or if you do not want to catch it.
 
Martijn Verburg
author
Bartender
Posts: 3275
5
Eclipse IDE Java Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Piyush Porwal wrote:From what I have read in the books, a try..catch block should consists of minimal code which can throw an exception. So if return is not expected to throw any exception, it should be outside of the try block. If you are doing something funky in the return like as simple as

then move it out only when you do not expect Dog constructor to throw an exception or if you do not want to catch it.


A great answer in my opinion , I've seen too many times where people simply wrap the entire code block in try/catch, not always necessary!
 
Amandeep Singh
Ranch Hand
Posts: 853
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
oh Yah I am returning a String. So it will never throw a exception. So it should be outside try and catch block. Great Answer. Thanks
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!