代码之家  ›  专栏  ›  技术社区  ›  elvis

在Java中尝试使用资源时,当抛出异常时关闭资源?[副本]

  •  -1
  • elvis  · 技术社区  · 1 年前

    在这段代码中,当br.close()中出现异常时,catch块会捕获它还是终止进程?

    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    
    public class TryWithBlock {
        public static void main(String args[])
        {
            System.out.println("Enter a number");
            try(BufferedReader br = new BufferedReader(new InputStreamReader(System.in)))
            {
                int i = Integer.parseInt(br.readLine());
                System.out.println(i);
            }
            catch(Exception e)
            {
                System.out.println("A wild exception has been caught");
                System.out.println(e);
            }
        }
    }
    
    0 回复  |  直到 3 年前
        1
  •  2
  •   DDS    3 年前

    docs :

    try with resources语句中声明的资源是 Buffered阅读器。声明语句出现在括号内 紧随try关键字之后。Java中的BufferedReader类 SE 7及更高版本实现了java.lang.AutoCloseable接口。 因为BufferedReader实例是在使用资源的try中声明的 语句,无论try语句是否正确,它都将被关闭 正常或突然完成(由于该方法 BufferedReader.readLine抛出IOException)。

    基本上,它相当于:

    BufferedReader br = new BufferedReader(new FileReader(System.in));
    try {
        int i = Integer.parseInt(br.readLine());
        System.out.println(i);
    } finally {
        br.close();
    }
    

    让我们尝试一下(从这里开始一个工作示例):

    //class implementing java.lang.AutoCloseable
    public class ClassThatAutoCloses implements java.lang.AutoCloseable {
    
        
        public ClassThatAutoCloses() {}
        
        public void doSomething() {
            
            System.out.println("Pippo!");
        }
        
        
        @Override
        public void close() throws Exception {
        
            throw new Exception("I wasn't supposed to fail"); 
            
        }
    
    }
    
    //the main class
    public class Playground {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            
            //this catches exceptions eventually thrown by the close
            try {
                
                try(var v = new ClassThatAutoCloses() ){
                    
                    v.doSomething();
                    
                }
            } catch (Exception e) {
                //if something isn't catched by try()
                //close failed will be printed
                System.err.println("close failed");
                e.printStackTrace();
            }
        }
    
    }
    
    //the output
    Pippo!
    close failed
    java.lang.Exception: I wasn't supposed to fail
        at ClassThatAutoCloses.close(ClassThatAutoCloses.java:26)
        at Playground.main(Playground.java:24)
    
        2
  •  -1
  •   NiVeR    3 年前

    try with resources语句中抛出的异常被抑制。try块内抛出的异常会被传播。因此,在您的情况下,catch块将捕获解析异常(如果有的话)。

    有关更多详细信息,请参阅 docs .