Confirmed users
586
edits
(add new section) |
(→Java Idioms: add idiom on closing resources) |
||
| Line 37: | Line 37: | ||
== Java Idioms == | == Java Idioms == | ||
=== Closing resources === | |||
A good way to ensure things get closed properly is to use a try/finally block like so: | |||
Cursor c = gimmeNewCursor(); | |||
try { | |||
useCursor(c); | |||
cursorMightThrowException(c); | |||
if (checkSomething(c)) { | |||
return extractReturnValue(c); | |||
} | |||
} catch (SomeSpecificException sse) { | |||
log(sse); | |||
} finally { | |||
if (c != null) { | |||
c.close(); | |||
} | |||
} | |||
Once the try block is entered, the finally block will *always* get executed upon exit of the try block. The one exception is if there is a System.exit call inside the try block, which immediately exits the program and makes everything moot anyway. The finally block will get executed on caught and uncaught exceptions, as well as normal returns. | |||
If you are casting the resource to something, make sure that you do the cast inside the try block, like so: | |||
// GOOD! | |||
InputStream is = getInputStream(); | |||
try { | |||
FileInputStream fis = (FileInputStream)is; | |||
... | |||
} finally { | |||
... | |||
} | |||
rather than doing this: | |||
// BAD! | |||
FileInputStream fis = (FileInputStream)getInputStream(); | |||
try { | |||
... | |||
} finally { | |||
... | |||
} | |||
This is so that in case of ClassCastExceptions you don't get a dangling open resource left behind. | |||