Is the FileNotFoundException somehow a "sub-exception" of the IOException?
This is my code opening an input stream to a file at the given path:
method(){
FileInputStream fs;
try {
fs = new FileInputStream(path);
//
fs.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
How come I can neglect the FileNotFound and just catch the IOException instead?
Is the FNFException a part of the IOException?
Instead of catching the exceptions, what if I throw an IOException in my method?
method() throws IOException{
FileInputStream fs;
fs = new FileInputStream(path);
//
fs.close();
}
Can I proceed to catch a FileNotFoundException at the invoking method like this?
try {
method();
}catch (FileNotFoundException e1) {}
Thanks for any help you might be able to provide!
解决方案
Is the FileNotFoundException somehow a "sub-exception" of the IOException?
Yes, FileNotFoundException extends IOException:
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.io.IOException
java.io.FileNotFoundException
How come I can neglect the FileNotFound and just catch the IOException instead?
Catching a base class of the exception being thrown will catch the exception, unless there is a more specific catch clause available.
Can I proceed to catch a FileNotFoundException at the invoking method like this?
Absolutely! In fact, this is a good thing to do: your code should handle only the exceptions with which it knows how to deal, and let all other exceptions propagate to a place where it could be dealt with in a better way.