1.3. Use try-with-resources - Source Code

Code:

package c1.s3;

/**
 * @author Mikalai Zaikin
 */
public class AutoCloseableResource implements AutoCloseable {

    @Override
    public void close() {
        System.out.println("in close()");
        throw new RuntimeException("Exception in close()");
    }

    public void work() throws Exception {
        System.out.println("in work()");
        throw new Exception("Exception in work()");
    }
}
					

Code:

package c1.s3;

/**
 * @author Mikalai Zaikin
 */
public class AutoCloseableTest {

    public static void main(String[] args) {
        try (AutoCloseableResource resource = new AutoCloseableResource()) {
            resource.work();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
					

output:

in work()
in close()
java.lang.Exception: Exception in work()
	at c1.s3.AutoCloseableResource.work(AutoCloseableResource.java:16)
	at c1.s3.AutoCloseableTest.main(AutoCloseableTest.java:10)
	Suppressed: java.lang.RuntimeException: Exception in close()
		at c1.s3.AutoCloseableResource.close(AutoCloseableResource.java:11)
		at c1.s3.AutoCloseableTest.main(AutoCloseableTest.java:11)
					

Code:

package c1.s3;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @author Mikalai Zaikin
 */
public class Copy {

    public static void copyFile(String src, String dest) throws IOException {
        try (BufferedReader in = new BufferedReader(new FileReader(src));
             BufferedWriter out = new BufferedWriter(new FileWriter(dest))) {
            String line;
            while ((line = in.readLine()) != null) {
                out.write(line);
                out.write('\n');
            }
        } // No need to close resources in a "finally"
    }
}
					

Professional hosting         Free 'Oracle Certified Expert Web Services Developer 6' Guide     Free SCDJWS 5.0 Guide