Search code examples
javafilenotfoundexceptionioexceptionfilewriterfileoutputstream

In java why does FileWriter throw IOException while FileOutputStream throw FileNotFoundException for the exact same reasons


From java docs

public FileWriter(String fileName) throws IOException

Throws:

IOException - if the named 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

and here

public FileOutputStream(File file, boolean append) throws FileNotFoundException

Throws:

FileNotFoundException - 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

Is there a specific reason for this choice?


Solution

  • Interesting question.

    I just peeked into each constructor's code, which helped clarify things:

    FileWriter uses a FileOutputStream. The FileOutputStream throws a FileNotFoundException, which extends IOException.

    FileWriter extends OutputStreamWriter whose constructor throws UnsupportedEncodingException, which also extends IOException.

    FileWriter, therefore, can throw either exception. But since they both extend IOException, it declares IOException in its constructor's signature.