Difference between catching exceptions using the Exception class or the FileNotFoundException class

As I have two scenarios where we have to handle FileNotFoundException

Option 1:

    try {
        FileInputStream fis = new FileInputStream("test1.txt");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } 

      

Case 2:

    try {
        FileInputStream fis = new FileInputStream("test1.txt");
    } catch (Exception e) {
        e.printStackTrace();
    }

      

In both cases, the printed stack trace is the same. I would like to know the difference between both implementations and which should be preferred?

+3


source to share


7 replies


From the docs, it gives the reason:

"A subclass inherits all members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the superclass's constructor can be called from the subclass."

The exception class is the parent of all other exception class. So if you know what you are going to get FileNotFoundException

, then it is helpful to use this exception. Creation Exception

is a common challenge.

This will help you understand:

enter image description here

So you can see that the Exception class is in a higher hierarchy, so it means that it will catch any exception other than FileIOExcetion. But if you want the attempt to open the file indicated by the specified pathname to fail, you must use FileIOExcetion.



So, here's what should be perfect:

try {
      // Lets say you want to open a file from its file name.
    } catch (FileNotFoundException e) {
      // here you can indicate that the user specified a file which doesn't exist.
      // May be you can try to reopen file selection dialog box.
    } catch (IOException e) {
      // Here you can indicate that the file cannot be opened.
    }

      

and the corresponding:

try {
  // Lets say you want to open a file from its file name.
} catch (Exception e) {
  // indicate that something was wrong
  // display the exception "reason" string.
}

      

Also check this: Is it really bad to catch a generic exception?

+5


source


In case 2, the catch block will run for everyone Exception

that is caught, no matter what they are. This allows you to handle all exceptions in the same way as displaying the same message for all types of exceptions.



In case 1, the block catch

will be started only for FileNotFoundException

. Catching specific exceptions in different blocks catch

allows you to handle different exceptions in different ways, such as displaying a different message to the user.

+1


source


When an exception is thrown, the JVM throws an Exception instance and that instance is passed to the appropriate catch block, so in catch(Exception e)

e it is only a reference variable, but the instance it points to has an Exception exception.

In the case, catch(FileNotFoundException e)

e is also a reference variable and the instance it points to has an Exception, so in both cases, different reference varibales (i.e. e) point to an instance of the same Exception (which is thrown).

this is what i prefer:

    try {
        // some task
    } catch (Exception e) {
        if (e instanceof FileNotFoundException) {

            // do this
        }
        if (e instanceof NullPointerException) {
            // do this
        } else {
            // do this
        }
    }

      

+1


source


It is a matter of what you want to intercept. With Exception

you will catch any exception, but with FileNotFoundException

you will only catch this error case, allowing the caller to catch and apply any handling.

0


source


Don't use them.

Don't catch Exception

. What for? Because it also catches all unhandled exceptions (i.e. RuntimeException

and derivatives). They must be rejected.

Don't use the old file API . What for? Because its exceptions are unreliable ( FileNotFoundException

can be thrown if you try to open a file that you don't have read access to, for example).

Use this:

final Path path = Paths.get("test1.txt");
try (
    final InputStream in = Files.newInputStream(path);
) {
    // do something with "in"
} catch (FileSystemException e) {
    // fs level error: no permissions, is a directory etc
} catch (IOException e) {
    // I/O error
}

      

You need to catch FileSystemException

before IOException

as the former is a subclass of the latter. Among other possible exceptions you can: AccessDeniedException

, FileSystemLoopException

, NoSuchFileException

etc.

0


source


The exception class is the parent of FileNotFoundException.

If you provided an exception in the catch statement, each exception will be handled in the catch block. But if FileNotFoundException is present in the catch block, only exceptions thrown because the File is not in the specified source, or permissions not readable by the file, or any such problem that could spoil Java's effort to read the file, will be handled. All other exceptions will be removed and moved up the stack.

In the code snippet you provided, it is good to use both. But I would recommend FileNotFoundException as it indicates the exact problem in the code.

For more details you can read Go here

0


source


When you write this:

  try {
        FileInputStream fis = new FileInputStream("test1.txt");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } 

      

The code inside the catch block is only executed if the exception (thrown inside the try block) is of type FileNotFoundException

(or subtype). When you write this, on the other hand:

try {
        FileInputStream fis = new FileInputStream("test1.txt");
    } catch (Exception e) {
        e.printStackTrace();
    }

      

the catch block is executed for any exception (since it Exception

is the root type of any exception).

If your file (test1.txt) does not exist, a FileNotFoundException is thrown and both code snippets can catch it. Try changing it to something like:

    try {
            FileInputStream fis = new FileInputStream("test1.txt");
        } catch (NullPointerException e) {
            e.printStackTrace();
        }

      

and you will see that the catch block is no longer executed.

0


source







All Articles