java try finally block to close stream

前端 未结 8 888
时光取名叫无心
时光取名叫无心 2020-12-05 17:25

I want to close my stream in the finally block, but it throws an IOException so it seems like I have to nest another try block in my finally<

8条回答
  •  南笙
    南笙 (楼主)
    2020-12-05 17:53

    It seems a bit clunky.

    It is. At least java7's try with resources fixes that.

    Pre java7 you can make a closeStream function that swallows it:

    public void closeStream(Closeable s){
        try{
            if(s!=null)s.close();
        }catch(IOException e){
            //Log or rethrow as unchecked (like RuntimException) ;)
        }
    }
    

    Or put the try...finally inside the try catch:

    try{
        BufferedReader r = new BufferedReader(new InputStreamReader(address.openStream()));
        try{
    
            String inLine;
            while ((inLine = r.readLine()) != null) {
                System.out.println(inLine);
            }
        }finally{
            r.close();
        }
    }catch(IOException e){
        e.printStackTrace();
    }
    

    It's more verbose and an exception in the finally will hide one in the try but it's semantically closer to the try-with-resources introduced in Java 7.

提交回复
热议问题