File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes return from catch Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "return from catch" Watch "return from catch" New topic
Author

return from catch

Drew Lane
Ranch Hand

Joined: May 13, 2001
Posts: 296
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

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
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

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
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: return from catch
 
Similar Threads
IBM Mock Exam: Try Catch Finally ?
question about return?
Little confusion in Finally block
Try an Finally Working Confusion
Return statement in try block