What is the use of the final block in an attempt to use resources (Java 7)?

The block finallyis mainly used to prevent resource leaks that can be achieved in the close()resource class method . Using a finally block with an operator try-with-resources, for example:

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");
        }
    }
}

Link: K.Seirra, B. Bates OCPJP Book

+4
source share
3 answers

As in the regular try-catch-finallyblock - block finally, it is used when you want something to always happen, regardless of whether the operation is performed in the block tryor not.

, , . , ( ), - . finally , .

, - try-with-resources catch , , , .

+3

finally , , JVM, .

, , , finally .

Java finally.

+1

This program will probably show you how the finally keyword works in Java and the importance of the finally keyword

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");


    }
}
0
source

All Articles