[JAVA] Use try-with-resources rather than try-finally

Resource close with try-finally

When handling some resources (InputStream, OutputStream, BufferedReader, etc.) in the try block, by calling the close method in the finally block before Java7, the resource regardless of whether the processing in the try block ended normally or abnormally. Was guaranteed to be closed securely. It looks like this:

protected void copy(String src, String dest) throws IOException {
	InputStream in = new FileInputStream(src);
	try {
		OutputStream out = new FileOutputStream(dest);
		try {
			byte[] buf = new byte[100];
			int n;
			while ((n = in.read(buf)) >= 0) {
				out.write(buf, 0, n);
			}
		} finally {
			out.close();
		}
	} finally {
		in.close();
	}
}

In addition, there are also checks to make sure that an exception does not occur in the finally block.

} finally {
	if (br != null)
		try {
			br.close();
		} catch (IOException e) {
			//Exception handling
		}
}

However, there are some problems with these writing styles.

Problem of resource closing in try-finally

Java 7 introduced the try-with-resources syntax for these issues. The try-with-resources syntax solves these problems all at once.

Resource close with try-with-resources

Immediately after the try, describe the resource generation process to be closed. If there are multiple resources to be closed, separate them with a semicolon.

protected void copy(String src, String dest) throws IOException {
	try (InputStream inputStream = new FileInputStream(src); OutputStream outputStream = new FileOutputStream(dest)) {
		byte[] buf = new byte[100];
		int n;
		while ((n = in.read(buf)) >= 0) {
			out.write(buf, 0, n);
		}
	}
}

By writing like this, the behavior will be as follows.

This solves the problems mentioned in "Problems with resource closing in try-finally".

Lesson

Use try-with-resources rather than try-finally when dealing with resources that must be closed

reference

Recommended Posts

Use try-with-resources rather than try-finally
[Swift] Use for where rather than nesting for and if