Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between catching exceptions using Exception class or FileNotFoundException class

Tags:

java

exception

Like i have these two scenarios where we have to handle FileNotFoundException

Case1:

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

Case2:

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

In both cases printed Stack Trace is same. I would like to know the difference between both implementations and what should be preferred ?

like image 420
quintin Avatar asked Jul 28 '26 19:07

quintin


1 Answers

From the docs it gives the reason:

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

Exception class is the parent of all the other exception class. So if you know that you are going to get the FileNotFoundException then it is good to use that exception. Making the Exception is a generic call.

This would help you understand:

enter image description here

So as you can see that the Exception class is at a higher hierarchy, so it means it would catch any exception other than the FileIOExcetion. But if you want to make sure that an attempt to open the file denoted by a specified pathname has failed then you have to use the FileIOExcetion.

So here is what an ideal approach should be:

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.
    }

while 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's "reason" string.
}

Also do check this: Is it really that bad to catch a general exception?

like image 64
Rahul Tripathi Avatar answered Jul 30 '26 08:07

Rahul Tripathi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!