Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

try/catch best practice

 
Dudley Dawson
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi- i have a method that returns a string, which is derived from another method that throws an exception:


p.process() throws an exception. if I place it within a try/catch block, then val is only in scope within that try/catch block, and I cannot return it outside of the block. If i put the return inside the block, I then have to put some other default return outside the block. Seems sloppy. Is there an elegant way to do this?
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Any objection to: -

 
Anupam Sinha
Ranch Hand
Posts: 1090
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would prefer



If need be initalize val to a default value.

It depends a lot on the program flow as well. Throwing the exception forward may also be a good idea depedning on where should the exception be handled.
 
Brian Spindler
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeah I agree with Anupam, if the exception is handled elsewhere you could write:



Or the same with handling in the method:


[ May 17, 2007: Message edited by: Brian Spindler ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic