whitehat
whitehat

Reputation: 2391

Why different exceptions for FileWriter and FileOutputStream?

The docs of Java 7 for FileWriter and FileOutputStream shows that the constructor of FileWriter throws IOException, while the constructor of FileOutputStream throws FileNotFoundException.

The reason for both the exceptions is same though. It says,"if the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason"

If this is the case, then why a specialized exception for FileOutputStream and a general exception for FileWriter is decided by Java creators??

Upvotes: 4

Views: 775

Answers (1)

casablanca
casablanca

Reputation: 70731

  1. FileWriter extends OutputStreamWriter whose constructor throws UnsupportedEncodingException.
  2. If you look at the implementation of FileWriter, it uses FileOutputStream which throws FileNotFoundException.

Because the FileWriter constructor can now throw either of these exceptions, it is declared to throw IOException, which is a common superclass for both exceptions. (Alternatively, it could have been declared to throw two individual exceptions.)

Upvotes: 4

Related Questions