Java – the difference between using the exception class or FileNotFoundException class to catch exceptions
Just like I have these two scenarios, we must deal with FileNotFoundException
Case 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 want to know the difference between the two implementations and what should be preferred?
Solution
Starting with docs, it gives the reason:
The exception class is the parent of all other exception classes Therefore, if you know you want to get FileNotFoundException, you'd better use it Making an exception is a generic phone
This helps you understand:
Therefore, you can see that the exception class is at a higher level, so it means that it will catch any exception except fileioexception However, if you want to ensure that the attempt to open the file represented by the specified pathname fails, you must use fileioexception
Therefore, this is an ideal method, which 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 @R_738_2419@. } 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's "reason" string. }
Is it really that bad to catch a general exception?