使用资源(Java 7)尝试使用finally块是什么意思?

时间:2016-03-18 10:02:32

标签: java try-with-resources

finally块主要用于防止可以在资源类的close()方法中实现的资源泄漏。使用带有try-with-resources语句的finally块是什么,例如:

class MultipleResources {

    class Lamb implements AutoCloseable {
        public void close() throws Exception {
            System.out.print("l");
        } 
    }

    class Goat implements AutoCloseable {
        public void close() throws Exception {
            System.out.print("g");
        } 
    }

    public static void main(String[] args) throws Exception {
        new MultipleResources().run();
    }

    public void run() throws Exception {
        try (Lamb l = new Lamb(); Goat g = new Goat();) {
            System.out.print("2");
        } finally {
            System.out.print("f");
        }
    }
}

参考:K.Seirra,B。Bates OCPJP Book

3 个答案:

答案 0 :(得分:3)

就像在常规try-catch-finally块中一样 - 当你想要总是发生某些事情时,使用finally块,无论try块中的操作是否成功。

我认为你的问题是提供一些真正有用的用例。尝试想象一种情况,当你必须告诉一个协作者(或发布一个事件)你的处理完成 - 无论结果如何。然后,您可以在finally块中输入可用于宣布完成处理的代码。

请注意,当try-with-resources块中没有catch的某些操作引发异常时,该块之后的代码将不会被执行。

答案 1 :(得分:1)

finally块中的代码总是被执行,除非执行代码或JVM的线程被终止。

这可以确保您分配的所有资源都会在finally中清除,无论如何。

Java doc详细解释了finally

答案 2 :(得分:0)

这个程序可能会向您展示Java中finally关键字的工作以及finally关键字

的重要性
class Example {
public static void main(String args[]) {
    int i = 1, j = 0;

    try {
        System.out.println("The result is " + i / j);
    }
    catch (ArrayIndexOutOfBoundsException e) {
        System.out.println("This is statement would never executed");
        System.out.println("Because catch() block is not catching exception from try");
    }
    finally {
        // finally block will always execute

        System.out.println("This statement will always executed");
        System.out.println("Becuase this is finally");
    }

    // These 3 statements would never executed
    // They will execute if catch block catches the Exception from try

    System.out.println("This is statement would never executed");
    System.out.println("Because catch() block is not catching exception from try");
    System.out.print(" and program is interrupted after finally");


    }
}