0

In this code, when there is an exception in br.close(), will catch block catch it or will the process be terminated?

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class TryWithBlock {
    public static void main(String args[])
    {
        System.out.println("Enter a number");
        try(BufferedReader br = new BufferedReader(new InputStreamReader(System.in)))
        {
            int i = Integer.parseInt(br.readLine());
            System.out.println(i);
        }
        catch(Exception e)
        {
            System.out.println("A wild exception has been caught");
            System.out.println(e);
        }
    }
}

2 Answers2

2

From the docs:

The resource declared in the try-with-resources statement is a BufferedReader. The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException).

Basically, it's equivalent to:

BufferedReader br = new BufferedReader(new FileReader(System.in));
try {
    int i = Integer.parseInt(br.readLine());
    System.out.println(i);
} finally {
    br.close();
}

Let's try it out (from here a working example):

//class implementing java.lang.AutoCloseable
public class ClassThatAutoCloses implements java.lang.AutoCloseable {

    
    public ClassThatAutoCloses() {}
    
    public void doSomething() {
        
        System.out.println("Pippo!");
    }
    
    
    @Override
    public void close() throws Exception {
    
        throw new Exception("I wasn't supposed to fail"); 
        
    }

}
//the main class
public class Playground {

    /**
     * @param args
     */
    public static void main(String[] args) {
        
        //this catches exceptions eventually thrown by the close
        try {
            
            try(var v = new ClassThatAutoCloses() ){
                
                v.doSomething();
                
            }
        } catch (Exception e) {
            //if something isn't catched by try()
            //close failed will be printed
            System.err.println("close failed");
            e.printStackTrace();
        }
    }

}
//the output
Pippo!
close failed
java.lang.Exception: I wasn't supposed to fail
    at ClassThatAutoCloses.close(ClassThatAutoCloses.java:26)
    at Playground.main(Playground.java:24)
DDS
  • 2,340
  • 16
  • 34
-1

Exceptions thrown inside the try-with-resources statement are supressed. Exceptions thrown inside the try block are propagated. So in your case the catch block will catch the parsing exception (if any).

For more details you can refer at the docs.

NiVeR
  • 9,644
  • 4
  • 30
  • 35