Why is a validation exception thrown

I notice that methods in some complex libraries, including the standard JDK, tend to throws

get elevated exceptions. I first found this phenomenon in the Apache POI source code, and then review it again in the java.io.FileWriter

following:

public FileWriter(String fileName) throws IOException {
    super(new FileOutputStream(fileName));
}

      

where the instance FileOutputStream

declares the only thrown exception FileNotFoundException

in this freeze frame. However IOException

, it is declared which is the superclass FileNotFoundException

.

So what is the reason for this? Or does it just depend on the habit of the programmer?

+3


source to share


1 answer


It might make sense to avoid changing the API too often.
Today the method can insert the subclass code IOexception

, but tomorrow it can throw out another one.



As long as the parent exception declared in the signature is not too general and will not lose value to clients, it seems like declaring the base class for the exception. For example, a bad use would be a declaration throw Exception

as the client could not understand the general meaning of the exception and handle it accordingly.

+5


source







All Articles