Java try-with-resources 块的异常处理语义与标准 Java try-catch-finally 块的异常处理语义略有不同。
在大多数情况下,更改后的语义比原始 try-catch-finally 代码块的语义更适合您,即使您并不确切了解两者的区别。即便如此,了解 try-with-resources 结构中异常处理的实际情况也不错的。因此,我将在这里解释一下 try-with-resources 结构的异常处理语义。
如果在 Java try-with-resources 块中抛出异常,在 try 块括号内打开的任何资源仍会自动关闭。异常的抛出将迫使执行离开 try 代码块,从而迫使资源自动关闭。一旦资源被关闭,从 try 代码块内部抛出的异常将在调用堆栈中向上传播。例如:
package com.hxstrive.jdk7.try_with_resources;
/**
* JDK7 新特性 try-with-resources
* @author hxstrive.com
*/
public class TryWithResourcesDemo4 {
static class MyResource implements AutoCloseable {
@Override
public void close() throws Exception {
// 即使 try-with-resources 代码块出现异常,这里也能执行
System.out.println("close");
}
public void doSomething(String message) {
System.out.println("doSomething() message=" + message.toUpperCase());
}
}
public static void main(String[] args) throws Exception {
try (MyResource resource = new MyResource()) {
resource.doSomething("hello");
resource.doSomething(null);
}
//结果:
//doSomething() message=HELLO
//close
//Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.toUpperCase()" because "message" is null
}
}