Okay, so I have a bunch of exception related questions across SO and Programmers, but there's just so much to ask, and either I don't know what to type, or not that many people have asked.
So, let's say I have a method that throws a FileNotFoundException
(FNFE). I then have another method that uses the first one, but also throws a IOException
(IOE).
My handler would catch both and do different things with each, but my IDE (IntelliJ) is signaling I have "a more general exception, 'java.io.IOException', in the throws list already".
I know it works if I do this:
public File openOrCreate(String pathStr) throws FileNotFoundException,
IOException {
try {
// Method that generates the FNFE
Path path = ReposioryProposition.getPath(pathStr);
File file = path.toFile();
catch (FileNotFoundException fnfe) {
throw fnfe;
}
if (!file.exists())
file.createNewFile(); // IOE
return file;
}
But do I need to do it explicitly? Will it work without, or more dangerously, will sometimes work without the explicit version.
To make sure we are on the same page, this is how I initially wrote the thing:
public File openOrCreate(String pathStr) throws FileNotFoundException,
IOException {
Path path = ReposioryProposition.getPath(pathStr);
File file = path.toFile();
if (!file.exists())
file.createNewFile();
return file;
}
But I am unsure what happens, is the FNFE thrown or swallowed up ? My intention is to catch them separately and do different stuff for one over the other.
You can't throw two exceptions. I.e. you can't do something like: try { throw new IllegalArgumentException(), new NullPointerException(); } catch (IllegalArgumentException iae) { // ... } catch (NullPointerException npe) { // ... }
Answer: No. You cannot throw the exception and also catch it in the same method. The exception that is declared using throws is to be handled in the calling method that calls the method that has thrown the exception.
You can either use the try-catch-finally approach to handle all kinds of exceptions. Or you can use the try-with-resource approach which allows an easier cleanup process for resources.
You only have to include the more general exception in your throws
list. This already specifies that the method may throw any subclass of this exception.
In particular, you must handle the more general exception anyway, and this exception handler will also handle the subclass. If you want to handle the subclass explicitly, you have to catch it before the more general exception:
try {
...
}
catch (FileNotFoundException e) {
// handle subclass
}
catch (IOException e) {
// handle general exception (this will not be executed if the
// exception is actually a FileNotFoundException
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With