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 Organizing Data Serialization

How 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
Samuel Ferree
31,722 Points

The 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
Samuel Ferree
31,722 Points

In 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();
}

Thank 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.