Note that you can also re-throw an exception. In many cases, it is perfectly reasonable to pass the error on to the next layer. If you also add a throws IOException
to your method, then it does not have to handle it. In many cases, the only way to handle such failures is to fail, and that should usually be done at the outermost level.
IDEs will remind you of missing throws
and suggest possible ways of resolving this. So the effort for the developer is pretty light compared to the benefit of having defined behavior on failure.
However it should be clear that the IDE not the compiler can predict the future, or the proper abstraction.
First of all, an interface or an abstract method can - and should - declare exceptions. For example:
interface Opener {
InputStream open(String id) throws IOException;
}
Reminding the user of this interface to handle such errors, for example file not found exceptions.
Furthermore, the compiler or IDE don't know the proper abstraction. Your code may do a
if (httpcode == 404)
throw new FileNotFoundException("Server returned a 404 error.");
But you don't know yet if you'll maybe later change this to a different exception, because it's not really a file. For example, you may want to have a subclass of a network exception. However, you may be sure that all exceptions that you intend to throw will be IOException
s, and hence require the user of that method to handle it at this level.
openFile
method but the file does not exist. There is no way for theopenFile
method to solve this, the user must do it. – Excursionist