FileNotFoundException in Java – Java中的FileNotFoundException

最后修改: 2016年 10月 7日


1. Introduction


In this article, we’re going to talk about a very common exception in Java – the FileNotFoundException.


We’ll cover the cases when it can occur, possible ways of treating it and some examples.


2. When Is the Exception Thrown?


As indicated on Java’s API documentation, this exception can be thrown when:


  • A file with the specified pathname does not exist
  • A file with the specified pathname does exist but is inaccessible for some reason (requested writing for a read-only file, or permissions don’t allow accessing the file)

3. How to Handle It?


First of all, taking into account that it extends that extends java.lang.Exception, you will need to deal with it with a try-catch block as with any other checked Exception.


Then, what to do (business/logic related) inside the try-catch block actually depends on what you need to do.


You may need to:


  • Rise a business-specific exception: this may be a stop execution error, but you will leave the decision in the upper layers of the application (don’t forget to include the original exception)
  • Alert a user with a dialogue or error message: this isn’t a stop execution error, so just notifying is enough
  • Create a file: reading an optional configuration file, not finding it and creating a new one with default values
  • Create a file in another path: you need to write something and if the first path is not available, you try with a fail-safe one
  • Just log an error: this error should not stop the execution but you log it for future analysis

4. Examples


Now we’ll see some examples, all of which will be based on the following test class:


public class FileNotFoundExceptionTest {

    private static final Logger LOG
      = Logger.getLogger(FileNotFoundExceptionTest.class);
    private String fileName = Double.toString(Math.random());
    protected void readFailingFile() throws IOException {
        BufferedReader rd = new BufferedReader(new FileReader(new File(fileName)));
        // no need to close file

    class BusinessException extends RuntimeException {
        public BusinessException(String string, FileNotFoundException ex) {
            super(string, ex);

4.1. Logging the Exception


If you run the following code, it will “log” the error in the console:

如果你运行以下代码,它将在控制台中 “记录 “错误。

public void logError() throws IOException {
    try {
    } catch (FileNotFoundException ex) {
        LOG.error("Optional file " + fileName + " was not found.", ex);

4.2. Raising a Business Specific Exception


Next, an example of raising a business-specific exception so that the error can be handled in the upper layers:


@Test(expected = BusinessException.class)
public void raiseBusinessSpecificException() throws IOException {
    try {
    } catch (FileNotFoundException ex) {
        throw new BusinessException(
          "BusinessException: necessary file was not present.", ex);

4.3. Creating a File


Finally, we’ll try to create the file so it can be read (maybe for a thread that is continuously reading a file), but again catching the exception and handling the possible second error:


public void createFile() throws IOException {
    try {
    } catch (FileNotFoundException ex) {
        try {
            new File(fileName).createNewFile();
        } catch (IOException ioe) {
            throw new RuntimeException(
              "BusinessException: even creation is not possible.", ioe);

5. Conclusion


In this quick writeup, we’ve seen when a FileNotFoundException can occur and several options to handle it.


As always, the full examples are over on Github.