Reputation: 191
public class ExceptionHandler {
public static void main(String[] args) throws FileNotFoundException, IOException {
// write your code here
try {
testException(-5);
testException(11);
} catch (FileNotFoundException e){
System.out.println("No File Found");
} catch (IOException e){
System.out.println("IO Error occurred");
} finally { //The finally block always executes when the try block exits.
System.out.println("Releasing resources");
testException(15);
}
}
public static void testException(int i) throws FileNotFoundException, IOException {
if (i < 0) {
FileNotFoundException myException = new FileNotFoundException();
throw myException;
}
else if (i > 10) {
throw new IOException();
}
}
}
The output of this code gives
No File Found
Releasing resources
Is it possible to have java catch both IOException as well as FileNotFoundException? It seems to be only able to catch the first exception and doesn't catch the IOException
Upvotes: 2
Views: 179
Reputation: 4065
You should enclose your try/catch/finally
block inside another try/catch
block because your finally
block can throw exceptions that must be captured.
Here is how your code works:
testException(-5)
throws a FileNotFoundException
FileNotFoundException
is catched by catch (FileNotFoundException e)
No File Found
is printed into the standard outputfinally
block is executed (the testException(10)
sentence is not executed).Releasing resources
is printedtestException(15)
is executed throwing an IOException
that is not captured anyway (the program will be interrupted).If you remove the throws FileNotFoundException, IOException
from your main
method the compiler will alert you that an exception is not being captured (the one in the finally
block).
Upvotes: 2
Reputation: 2078
The try
block stops at the first exception thrown, therefore the second call of testException()
is never executed.
Upvotes: 3