美文网首页
try-catch语句块和 AutoCloseable接口

try-catch语句块和 AutoCloseable接口

作者: KeepYeung杨 | 来源:发表于2018-11-06 22:17 被阅读0次

    早期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接口。

    相关文章

      网友评论

          本文标题:try-catch语句块和 AutoCloseable接口

          本文链接:https://www.haomeiwen.com/subject/ytepxqtx.html