Back
Featured image of post try-with-resources优先于try-finally

try-with-resources优先于try-finally

Java Learning

Reading Day

try-with-resources是jdk1.7引入的语法,使得关闭资源操作无需层层嵌套在finally

当try-finally关闭资源时,其出现了两处异常,往往只会返回第一处异常。

当java7开始引入try-with-resources后,这些问题就迎刃而解了。不过使用这个结构的时候,必须接入AutoCloseable接口

其中包括了单个返回void的close方法。现在Java库与第三方类库中的许多类和接口都实现了或拓展了AutoCloseable接口

Try-Catch-Finally 结构

可见,我们需要手动关闭两个Stream资源。而且为了防止异常的产生而无法关闭,需要借助finally正常关闭资源

public class DemoTest {
    public static void main(String[] args) {
        	BufferedInputStream bin = null;
			BufferedOutputStream bout = null;
			try {
				bin = new BufferedInputStream(new FileInputStream(new File("test.txt")));
				bout = new BufferedOutputStream(new FileOutputStream(new File("out.txt")));
				int b;
				while ((b = bin.read()) != -1) {
					bout.write(b);
				}
			}
			catch (IOException e) {
				e.printStackTrace();
			}
			finally {
				if (bin != null) {
					try {
						bin.close();
					}
					catch (IOException e) {
						throw e;
					}
					finally {
						if (bout != null) {
							try {
								bout.close();
							}
							catch (IOException e) {
								throw e;
							}
						}
					}
				}
			}
		}
	}

Try-with-resources结构

而在try-with-resources中,我们只需要这样,编译器会帮我们自动补全close(),并且还会将异常正确报出,而不会由于嵌

套只指出一处异常。

public class TryWithResource {
    public static void main(String[] args) {
        try (BufferedInputStream bin = new BufferedInputStream(new FileInputStream(new File("test.txt")));
             BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(new File("out.txt")))) {
            int b;
            while ((b = bin.read()) != -1) {
                bout.write(b);
            }
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
}

反编译class , 可见close()的补全

public class TryWithResource {
    public TryWithResource() {
        
    }
    public static void main(String[] args) {
        try {
            Connection conn = new Connection();
            Throwable var2 = null;
            try {
                conn.sendData();
            } catch (Throwable var12) {
				var2 = var12;
				throw var12;
			} finally {
				if (conn != null) {
					if (var2 != null) {
						try {
							conn.close();
						} catch (Throwable var11) {
							var2.addSuppressed(var11);
						}
					} else {
						conn.close();
					}
				}
			}
		} catch (Exception var14) {
			var14.printStackTrace();
		}
    }
}
Maybe it can be made by mz
Welcome to the world of Minezeratul