为减少程序员写代码的工作量,而设计的语法。对于执行器而言,要做的功能并没有变化,只是在编写程序时代码量减少了。
try{
会抛出异常的代码;
}catch(Exception e){
异常处理;
}finally{
关闭资源;
}
try(资源声明及初始化){
会抛出异常的代码;
}catch(Exception e){
异常处理;
}
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class TestTryWithResource {
public static void main(String[] args) {
//try...catch...finally写法
FileReader reader = null;
try{
reader = new FileReader(new File("d:/log.txt"));
int read = reader.read();
System.out.println(read);
}catch (Exception e){
e.printStackTrace();
}finally {
if(reader != null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//try...with...resource写法
try(FileReader reader2 = new FileReader(new File("d:/log.txt"));){
int read = reader2.read();
System.out.println(read);
}catch (Exception e){
e.printStackTrace();
}
}
}
编译后的class文件内容,原本需要由程序员做的事,现在改为由编译器做了。
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class TestTryWithResource {
public TestTryWithResource() {
}
public static void main(String[] args) {
FileReader reader = null;
try {
reader = new FileReader(new File("d:/log.txt"));
int read = reader.read();
System.out.println(read);
} catch (Exception var29) {
var29.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException var26) {
var26.printStackTrace();
}
}
}
try {
FileReader reader2 = new FileReader(new File("d:/log.txt"));
Throwable var3 = null;
try {
int read = reader2.read();
System.out.println(read);
} catch (Throwable var28) {
var3 = var28;
throw var28;
} finally {
if (reader2 != null) {
if (var3 != null) {
try {
reader2.close();
} catch (Throwable var27) {
var3.addSuppressed(var27);
}
} else {
reader2.close();
}
}
}
} catch (Exception var32) {
var32.printStackTrace();
}
}
}