Why are there different exceptions for FileWriter and FileOutputStream?

The Java 7 docs for FileWriter and FileOutputStream show that the FileWriter constructor throws an IOException, and the FileOutputStream constructor throws a FileNotFoundException.

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

If so, why are the specialized exception for FileOutputStream and the general exception for FileWriter solved by Java developers?

+4
source share
1 answer
  • FileWriter extends OutputStreamWriter , whose constructor throws an UnsupportedEncodingException .
  • If you look at the implementation of FileWriter , it uses a FileOutputStream that throws a FileNotFoundException .

Because the FileWriter constructor can now throw any of these exceptions, throw IOException declared, which is the common superclass for both exceptions. (Alternatively, two separate exceptions could be declared.)

+4
source

Source: https://habr.com/ru/post/1392612/


All Articles