try-catch语句块和 AutoCloseable接口

早期java捕捉异常的语法是这样的:

try{
//do something
}catch(Exception e){
//handle it
}finally{

}

而到了JDK7之后,可以使用try-with-resources和multiple catch:

try(FileInputStream inputStream = new FileInputStream(new File("test")){//try-with-resources
//do something..
}catch(IOException | Exception e){//multiple catch
//handle it
}finally{
...
}

若在try()中定义多个资源的话,用分号隔开。
在try-catch-resources语句中,会先关闭try()中的资源,然后执行catch块的语句,再执行finally块中的语句。

try(FileInputStream inputStream = new FileInputStream(new File("test");Resource resource = new Resource()){ 
//do something
}catch(Exception e){

}finally{

}

在try-with-resources语句中,AutoCloseable会被调用并自动释放资源。资源关闭的顺序和资源定义的顺序相反。
InputStream和OutputStream都继承了AutoCloseable
如果是自己定义的类,需要实现AutoCloseable接口。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。