Expand Authors Top

If you have a few years of experience in the Java ecosystem and you’d like to share that with the community, have a look at our Contribution Guidelines.

Expanded Audience – Frontegg – Security (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

Java Top

Get started with Spring 5 and Spring Boot 2, through the Learn Spring 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)));
        // 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.

Java bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

Generic footer banner
Comments are closed on this article!