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 trialChitra Sharathchandra
6,188 PointsHow do we know which exceptions to catch?
Hello,
The video shows exceptions for the I/O streams but how do we know which exceptions must be "caught" and what the order is?
Thanks, Chitra
2 Answers
Samuel Ferree
31,722 PointsThe Java compiler should actually complain with an error if an Exception is uncaught. (Again, aside from RuntimeExceptions)
However, if the method containing the code declares itself that it may throw an exception, the compiler won't warn you.
Samuel Ferree
31,722 PointsIn Java, with the exception of RuntimeExceptions (and it's subclasses), methods must explicitly state which exceptions they are might throw. The documentation for the library or framework you are using usually contains this information. Your editor might also be able to tell you which exception a given method may throw.
If you aren't sure, you can generically catch any Exception. This will work unless you need to respond to different exceptions differently. Usually though, error handling is generic enough to only need one catch statement, like so.
try
{
//call methods that might throw exceptions
}
catch (Exception e)
{
//log the error to the console and move on
e.printStackTrace();
}
Chitra Sharathchandra
6,188 PointsThank you! So, sounds like it is important to look for library documentation to ensure that we have at least one exception for the catch block.