In try with resources in java, what happens when there is an exception in close() when there is a catch block? [duplicate]
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);
}
}
}
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)