• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

return from catch

 
Drew Lane
Ranch Hand
Posts: 296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not sure I totally understand what happens when I use keyword 'return' in a catch block.
For example, say I'm reading a file and I catch the exception and just return:
try {
fis = new FileInputStream("myfile");
} catch(FileNotFoundException e) {return;}
Where does the exception go?
Is it bad practice to use return in a catch block?
When/How is this used?
Thanks,
Drew
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Where does the exception go?

You caught it, end of the line.


Is it bad practice to use return in a catch block?

Yes, no, maybe. It all depends on the application. The problem with the code you posted is that the method just silently blows up. The user has no idea what happened. You could have accomplished the same thing with an empty catch block (no return at all). At a minimum you should somehow log the exception or let the user know that the file does not exist.
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
We've had the discussion on returning from a try/catch/finally block and I don't think a concensus was reached, but personally this is something I will never do. It works fine with just a try/catch, but if you add a finally block too, you can create non-determanistic code. That is: code which you have no idea what it does without testing all possible paths.
I won't go into too many details, but what happens when a catch block returns and the finally throws an Exception? What about the opposite? What if the both return or both throw exceptions? Pretty bad code, but I've had to maintain gumph like this
 
Drew Lane
Ranch Hand
Posts: 296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by David O'Meara:
Pretty bad code, but I've had to maintain gumph like this

Yeah, I came across this in some code that somebody wrote I was thinking "what the heck is this?"
That's kinda what got me thinking about it...
Drew
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic