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
Joined: Jan 30, 2002
Posts: 3451
posted
0
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.
Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
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
Joined: May 13, 2001
Posts: 296
posted
0
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