Brain Teaser – Guess which exception is thrown?

Guess I :- Which exception is thrown to the outer world? Exception of try block or exception of Finally block?

public void FilePrinting() throws IOException {
    InputStream input = null;

    try {
        input = new FileInputStream("file.txt"); //if exception thrown here
        int data = input.read();
        while(data != -1){
            System.out.print(data);
            data = input.read();
        }
    } finally {
        if(input != null){
            input.close(); // if exception also thrown here
        }
    }
}
  • Exception is thrown inside try block (highlighted in red).
  • Finally block will always execute and exception is also thrown inside finally block.
  • The exception thrown from the finally block would be propagated up the call stack, even if the exception thrown from the try block would probably be more relevant to propagate.

Guess 2 : Which exception is thrown now? Exception of try block or exception of Finally block?

public void FilePrinting() throws IOException {
    InputStream input = null;
// Try with resource is implemented
    try(FileInputStream input = new FileInputStream("file.txt")) {
        int data = input.read();
        while(data != -1){
            System.out.print((char) data);
            data = input.read();
        }
    } finally {
        if(input != null){
            input.close(); // if exception also thrown here
        }
    }
}
  • Try with resources is implemented
  • The FileInputStream variable is declared inside the parentheses after the try keyword.
  • An Exception is thrown inside the try-with-resources block.
  • Exception is also thrown inside finally block.
  • The exception thrown inside the try block is thrown to the outside world instead of exception thrown inside finally block.




Read More :- Difference in interface of JAVA7, JAVA8 and JAVA9?


java 10 features value type

Leave a Reply

Your email address will not be published. Required fields are marked *