• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

Best Practice where to write return statement?

 
Ranch Hand
Posts: 856
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
author
Posts: 3281
8
Mac OS X Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 856
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Normally trees don't drive trucks. Does this tiny ad have a license?
free, earth-friendly heat - a kickstarter for putting coin in your pocket while saving the earth
https://coderanch.com/t/751654/free-earth-friendly-heat-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic