close ()
callClose () processing that was written using try-finally as follows in Java 6 or earlier
Closeable r = null;
try {
//Secure resources
r = getResource();
//Use resources
r.use();
} finally {
if (r != null) r.close();
}
However, from Java 7, it has become very smart with the following writing style.
//Secure resources
try (Closeable r = getResource()) {
//Use resources
r.use();
}
You know the try-with-resources syntax.
Closeable.close ()
throws ʻIOException`Now, with the above code fragment, when you try the actual programming, you will notice that some important points are omitted. Yes, it doesn't handle the throwing of ʻIOException. In particular, the latter code using the try-with-resources syntax, neither
getResource () nor ʻuse ()
throws ʻIOException, but overall throws ʻIOException
. Because there is a close ()
call that is not visible in syntactic sugar. close ()
throws ʻIOException` and we need to handle it.
So the latter is actually
//Secure resources
try (Closeable r = getResource()) {
//Use resources
r.use();
} catch (IOException e) {
//Appropriate processing
}
It must be in the form of. Or do you throw it higher with throws IOException
? Either way, the code will be a bit noisier than you expected from the original touch.
So far, if you've used the try-with-resources syntax even once, you've probably already noticed.
close ()
that does not throw ʻIOException`Now the main subject is from here.
The story is that you can make the following simple code without using catch
or throws
.
//Secure resources
try (MyResource r = getResource()) {
//Use resources
r.use();
}
It is possible to have a Closeable
/ ʻAutoCloseable class where
close () will always succeed. So, while implementing
Closeable` when creating such a class by myself
public class MyResource implements Closeable {
public void close() {
//Close process that always succeeds
}
}
And write close ()
without throws IOException
. The interface implementation is valid without throws IOException
. And if this class is a resource
//Secure resources
try (MyResource r = getResource()) {
//Use resources
r.use();
}
Will not throw a check exception.
It's natural to notice, but when using the IDE, throws IOException
is automatically written from the beginning, so it is left attached even though it is unnecessary, and as a result, unnecessary catch
is forced. It seems that it is rare, so even a warning.
Recommended Posts