Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4536

FileNotFoundException in Java

$
0
0

The Master Class of "Learn Spring Security" is live:

>> CHECK OUT THE COURSE

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  java.io.IOException 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)));
        rd.readLine();
        // 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:

@Test
public void logError() throws IOException {
    try {
        readFailingFile();
    } 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 {
        readFailingFile();
    } 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:

@Test
public void createFile() throws IOException {
    try {
        readFailingFile();
    } catch (FileNotFoundException ex) {
        try {
            new File(fileName).createNewFile();
            readFailingFile();            
        } 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.

I just released the Master Class of "Learn Spring Security" Course:

>> CHECK OUT THE COURSE


Viewing all articles
Browse latest Browse all 4536

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>