Java7新特性 try-with-resource
2018-03-20 22:11
603 查看
package com.zxc.csdn; /** * @author russell */ public class ResExceptionDemo { public static void main(String[] args){ try(ResException resException=new ResException()){ resException.doSomething(); }catch (Exception e){ e.printStackTrace(); } } } class ResException implements AutoCloseable{ public void doSomething(){ System.out.println("doing..."); } @Override public void close() throws Exception { System.out.println("close!"); } }
try-with-resource的出现是为了避免在语句(文件资源操作类)中抛出异常而导致后面的资源关闭方法(close())无法正常执行,引起错误。
使用try-with-resource的前提是资源类必须实现AutoCloseable接口,如果想清除一些没有实现AutoCloseable接口的资源,则使用finally字句
package com.zxc.csdn; /** * @author russell */ public class NormalTryException { public static void main(String[] args){ TryException tryException=new TryException(); try{ tryException.doSomething(); }catch (Exception e){ e.printStackTrace(); }finally { if(tryException !=null){ try{ tryException.close(); }catch (Exception e){ e.printStackTrace(); } } } } } class TryException{ public void doSomething(){ System.out.println("doing..."); } public void close() throws Exception { System.out.println("close!"); } }
要注意资源类实例的创建要放在try语句块外部,否则finally字句无法访问该实例,同时注意close方法也会抛出异常,因此通常将复杂的try/catch/finally语句改为try-with-resource,或者在try/finally语句中嵌套try/catch语句
相关文章推荐
- Java新特性-try-with-resource
- java 7 新特性之一 try with resource statement
- java7 try-with-resource
- Java新特性之try-with-resources实践
- 使用Java中的Try-With-Resource
- [Java开发之路](20)try-with-resource 异常声明
- java新特性之try-with-resources
- 深入理解Java try-with-resource【细节2】
- 深入理解 Java 中的 try-with-resource
- java 7新特性-TWR(Try-with-resources)
- 深入理解 Java 中的 try-with-resource
- Java进阶知识点3:更优雅地关闭资源 - try-with-resource及其异常抑制
- 深入理解 Java 中的 try-with-resource
- 深入理解 Java try-with-resource 语法糖
- Java新特性之try-with-resources语句
- Java 7 新特性try-with-resources语句
- Effective Java 3rd 条目9 try-with-resource优于try-finally
- java-资源管理器try-with-resource
- 深入理解 Java 中的 try-with-resource
- java - try with resource