Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Data Structures - Retired Efficiency! Implement Chooser UI

Is it better to throw/catch exceptions or program defensively?

When prompting the user to make a song selection, we add a throws IOException to the method signature. How do we decide when to handle exceptions internally versus throwing them up to the calling routine?

Also, if we had used a Scanner instead of a BufferedReader, we could test the user input with mReader.hasInt() and give him/her the chance to try again, without catching an exception. Then again, perhaps any method that reads from System.in or from a file has checked exceptions of one kind or another and so using try...catch is unavoidable.

Thanks

1 Answer

Generally speaking, it is usually best to handle the exceptions as soon as possible, rather than throwing them around. I really can't think of a creative example here, but if you get an exception in a class who's role or task isn't related to the exception generated, then there might not always be an easy way or useful way to deal with that exception within that class, in which case you should pass it up the chain where it makes sense to handle it. Otherwise I'd say you should pretty much always catch them as soon as they're generated.

As for your second question, I'd say it's always good to avoid exception handling where possible - but wherever there is input or output there is almost always a possibility for some kind of exception - checked or unchecked. So you'd have to handle those anyway. But sure, some redundancy to prevent an exception can't hurt.