try-with-resources使用

try-with-resources声明

  JDK1.7开始,java引入了 try-with-resources 声明,将 try-catch-finally 简化为 try-catch;

  1、新的声明包含三部分:try-with-resources 声明、try 块、catch 块;
  2、要求在 try-with-resources 声明中定义的变量实现了 AutoCloseable 接口,这样在系统可以自动调用它们的close方法,从而替代了finally中关闭资源的功能。

try-catch-finally 异常处理有两种情况:
  1. try 块没有发生异常时,直接调用finally块,如果 close 发生异常,就处理。
  2. try 块发生异常,catch 块捕捉,进行第一处异常处理,然后调用 finally 块,如果 close 发生异常,就进行第二处异常处理。
try-with-resources 结构中,异常处理也有两种情况:
  1. try 块没有发生异常时,自动调用 close 方法,如果发生异常,catch 块捕捉并处理异常。
  2. try 块发生异常,然后自动调用 close 方法(所有close()都执行),如果 close 也发生异常,catch 块只会捕捉 try 块抛出的异常,close 方法的异常会在catch 中被压制,但是你可以在catch块中,用 Throwable.getSuppressed 方法来获取到压制异常的数组。
  3. 任何 catch 或 finally 块在声明的资源 后再执行。
public class TestTWR {

	public static void startTest() {
		try (MyAutoCloseA a = new MyAutoCloseA();
			MyAutoCloseB b = new MyAutoCloseB()) {
			a.test();
			b.test();
		} catch (Exception e) {
			System.out.println("TestTWR: exception");
			System.out.println(e.getMessage());

			Throwable[] suppressed = e.getSuppressed();
			for (int i = 0; i < suppressed.length; i++)
			System.out.println(suppressed[i].getMessage());
		}
	}

	public static void main(String[] args) throws Exception {
		startTest();
	}
}

/* 输出为:
    ResourceA: test()
    ResourceB: on close
    ResourceA: on close()
    TestTWR: exception
    ResourceA: test() IOException
    ResourceB: close() ClassNotFoundException
    ResourceA: close() ClassNotFoundException
*/

class ResourceA implements AutoCloseable {

	public void test() throws IOException {
		System.out.println("ResourceA: test()");
		throw new IOException("ResourceA: test() IOException");
	}

	@Override
	public void close() throws Exception {
		System.out.println("ResourceA: on close()");
		throw new ClassNotFoundException("ResourceA: close() ClassNotFoundException");
	}
}

class ResourceB implements AutoCloseable {

	public void test() throws IOException {
		System.out.println("ResourceB: test()");
		throw new IOException("ResourceB: test() IOException");
	}
	
	@Override
	public void close() throws Exception {
		System.out.println("ResourceB: on close");
		throw new ClassNotFoundException("ResourceB: close() ClassNotFoundException");
	}
}
总结:
  1. catch 块中,看不到 try-with-recourse 声明中的变量。
  2. try-with-recourse 中,try 块中抛出的异常,在 e.getMessage() 可以获得,而调用 close() 方法抛出的异常在e.getSuppressed() 获得。
  3. try-with-recourse 中定义多个变量时,使用分号分割,关闭的顺序是从后往前,并且全部关闭
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值