-3

The constructor Formatter(String fileName) doesn't seem to compile when I don't handle FileNotFoundException even if the file already exists.

Here's the code that works:

import java.util.*;

public class CreatingFiles {

public static void main(String[] args) {
    final Formatter MYFILE;

    try {
        MYFILE = new Formatter("john.txt");
        System.out.println("File created");
    }

    catch (Exception e) {
        System.out.println("Error!");
    }
  }
}

However when I remove the try/catch block:

import java.util.*;

public class CreatingFiles {

public static void main(String[] args) {
    final Formatter MYFILE;

    MYFILE = new Formatter("john.txt");
  }
}

The compiler tells me that I have to either throw or catch the exception. So why doesn't it work without handling the exception?

3 Answers3

2

The constructor Formatter(String) [https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#Formatter(java.lang.String)], throws a FileNotFound exception [https://docs.oracle.com/javase/7/docs/api/java/io/FileNotFoundException.html], a checked exception [https://en.wikibooks.org/wiki/Java_Programming/Checked_Exceptions], so you have to catch it or re-throw it.

Andrea Colleoni
  • 5,919
  • 3
  • 30
  • 49
0

https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#Formatter(java.lang.String)

SecurityException - If a security manager is present and checkWrite(fileName) denies write access to the file

FileNotFoundException - If the given file name does not denote an existing, writable regular file and a new regular file of that name cannot be created, or if some other error occurs while opening or creating the file

Compiler don't know if the file exist. It will find only at execution.

You can put throws ExceptionName in method declaration

public void MyMethod() throws ExceptionName{
    //TODO
}

but will be throwed to the caller of this method.

Community
  • 1
  • 1
KunLun
  • 3,109
  • 3
  • 18
  • 65
0

A FileNotFoundException is a checked exception, meaning that you must be able to recover from it, i. e. display a message like The file could not be opened. Users frequently delete files, hence, you cannot be sure that the file you are requesting actually exists. However, it would be a really bad experience for the user if your application crashed only due to the file not being present.

For that reason, the compiler forces you to handle the case that the file you are requesting does not exist. Most probably, you should only display some kind of error message to the user and log the exception maybe.

I found this explanation of checked exceptions to be very helpful in case you have further questions.

vatbub
  • 2,713
  • 18
  • 41