Yes, you should document all the exceptions that a method can throwmethod's clients are expected to handle. Where exactly the exceptions originate is irrelevant - even if they come from some methodC()
which happens to be called by methodB()
.
Code calling methodA()
shouldn't care what other methods it calls in order to get the job done, but it does need know about the things that might go wrong.
In your example, since methodA()
doesn't take responsibility for handling the FileNotFound
or ResourceNotFound
exceptions, any code calling methodA()
needs to know that it has to deal with those scenarios.
Now, if methodA()
can take some sensible action in the case of a FileNotFound
or ResourceNotFound
exception, then it should do that and it doesn't need to report those exceptions - it can hide them from its clients.
A simple example, in Java: (For the sake of argument, let's agree that a non-existent file is 0 bytes long)
int getFileSize(String filename) { try { return getFileBytes(filename).length; } catch (FileNotFoundException e) { return 0; } } byte[] getFileBytes(String filename) throws FileNotFoundException { // ... }
Edit
As Illustrated by Bobson's comment, I've feel I've misrepresented a very important point - see the change in bold above!
There are generally 3 cases where an exception/error should thrown:
- Things you can reasonably expect to go wrong. e.g. Trying to print something but you can't get access to a printer, or you're trying to open a file which doesn't exist.
- Programming errors - i.e. bugs. e.g. Dividing by 0, NullPointerExceptions. These shouldn't be making it into released code so you generally shouldn't be writing code to deal with them.
- Unrecoverable errors. e.g. StackOverflowError. These tend to be thrown by the underlying system (virtual machine, OS, etc.) and generally there isn't anything you can do about them.
The ones you should be declaring are those in category 1. Java tries to force you to do this, but it does have some problems.