I notice that methods in some sophisticated libraries, including the standard JDK, tend to throws
upcasting exception. At first I found this phenomenon in the source code of Apache POI, later see it again in java.io.FileWriter
like this:
public FileWriter(String fileName) throws IOException {
super(new FileOutputStream(fileName));
}
where the instantiation of FileOutputStream
declares the only checked exception FileNotFoundException
in the this callstack. However, IOException
is declared, which is the super class of FileNotFoundException
.
So what is the reason for this? Or does it simply depend on the habit of programmer?
It may make sense to avoid changing the API too frequently.
Today, a method can throw in the code a subclass of IOexception
but tomorrow it could throw another one.
While the parent exception declared in the signature is not too general and doesn't loose value for the clients, it seems ok to declare a base class for the exception.
For example, a bad use would be to declare throw Exception
as the client could not understand the general meaning of the exception and handle it consequently.