There's no clear-cut answer to your question. What exceptions a method should catch and handle, and how, is entirely dependent on the contract and semantics of that particular method.
Take for example Google Guava's Ints.tryParse
method. It's implemented like this:
public static Integer tryParse(String s) {
try {
return Integer.parseInt(s);
} catch (NumberFormatException e) {
return null;
}
}
Since its contract specifies that it returns null
for strings that can't be parsed, it must catch the exception.
On the other hand, you might have some method that fetches a file on the Internet and writes its content to disk. If that method fails, it would make sense to throw MalformedURLException
, IOException
etc depending on what went wrong, so that the client code can act accordingly.
try/catch
and athrows
clause for the same exception? Seems a bit redundant. \$\endgroup\$