Java | 原来 try 还可以这样用啊?!

 

习惯了这样的try:

1 try
2 {
3 
4 } catch (Exception e)
5 {
6 }

 

看到了这样的try,觉得有点神奇:

1 try(...)
2 {
3 } catch (Exception e) 
4 {
5 }

 

原来这还有个专业术语, try-with-resources statement ,它会自动关闭括号内的资源(resources),不用手动添加代码   xx.close();  了。

 

看个小例子:

复制代码
 1 package org.young.elearn;
 2 
 3 import java.io.FileOutputStream;
 4 import java.io.IOException;
 5 
 6 import org.junit.Test;
 7 
 8 /**
 9  * try-with-resources 的使用
10  * try(resouces)
11  * {
12  * 
13  * } catch (Exception e){}
14  * 
15  * 这里的resource会自动关闭
16  * 
17  * 1. resource 必须继承自 java.lang.AutoCloseable
18  * 2. 定义和赋值必须都在try里完成
19  * 
20  * 
21  *
22  * @author by Young.ZHU
23  *      on 2016年5月29日
24  *
25  * Package&FileName: org.young.elearn.TryWithResourcesTest
26  */
27 public class TryWithResourcesTest {
28     
29     /**
30      * 验证一下资源是不是真的关闭了
31      */
32     @Test
33     public void test() {
34 
35         try (MyResources mr = new MyResources()) {
36 //            mr.doSomething(4);
37             mr.doSomething(9);
38         } catch (Exception e) {
39             System.out.println(e.getMessage());
40         }
41     }
42     
43     /**
44      * 编译错误:
45      * The resource f of a try-with-resources statement cannot be assigned
46      */
47     @Test
48     public void test2() {
49         try (FileOutputStream f = null;) {
50 //            f = new FileOutputStream(new File(""));
51         } catch (IOException e) {
52             e.printStackTrace();
53         }
54     }
55 
56     /**
57      * 编译错误:
58      * The resource type File does not implement java.lang.AutoCloseable
59      */
60     @Test
61     public void test1() {
62         /*try (File file = new File("d:\\xx.txt");) {
63             
64         } */
65     }
66 
67 }
68 
69 class MyResources implements AutoCloseable {
70 
71     @Override
72     public void close() throws Exception {
73         System.out.println("resources are closed.");
74     }
75     
76     public void doSomething(int num) throws Exception {
77         if (num % 2 == 0) {
78             System.out.println("it's OK.");
79         } else {
80             throw new Exception("Enter an even.");
81         }
82     }
83 }
复制代码

 

以后使用 InputStream,OutputStream 之类的就方便一点了,具体可参考另一个例子:GitHub

 

 阅读原文

posted on   Memory4Young  阅读(7709)  评论(0编辑  收藏  举报

编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
历史上的今天:
2015-06-01 [git/GitHub] git push 时报错:fatal: remote error: You can't push to git://github.com/user/xxx.git(已解决)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示