在这段代码中,当br.close((中出现异常时,catch块会捕获它还是终止进程?
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);
}
}
}
来自文档:
try-with-resources语句中声明的资源是BufferedReader。声明语句出现在括号内紧接在try关键字之后。Java中的BufferedReader类SE 7及更高版本实现了接口java.lang.AutoCloseable。因为BufferedReader实例是在带有资源的try中声明的语句,无论try语句是否为,它都将被关闭正常或突然完成(由于该方法BufferedReader.readLine引发IOException(。
基本上,它相当于:
BufferedReader br = new BufferedReader(new FileReader(System.in));
try {
int i = Integer.parseInt(br.readLine());
System.out.println(i);
} finally {
br.close();
}
让我们尝试一下(从这里开始一个工作示例(:
//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)
禁止在try-with-resources语句中抛出异常。在try块内部引发的异常会被传播。因此,在您的情况下,catch块将捕获解析异常(如果有的话(。
有关更多详细信息,请参阅文档。