leongwq
leongwq

Reputation: 191

Java catch different exceptions

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

Answers (2)

Paco Abato
Paco Abato

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
  • FileNotFoundExceptionis catched by catch (FileNotFoundException e)
  • No File Found is printed into the standard output
  • Then finally block is executed (the testException(10) sentence is not executed).
  • So Releasing resources is printed
  • And testException(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

Matei Radu
Matei Radu

Reputation: 2078

The try block stops at the first exception thrown, therefore the second call of testException() is never executed.

Upvotes: 3

Related Questions