3 ms·
Java 7 introduced a new language construct, called the try-with-resources statement, for automatic resource management: void foo() { try (open file
by applecore 13y ago
Java 7 introduced a new language construct, called the try-with-resources statement, for automatic resource management:
void foo() {
try (open file or resource here) {
// do stuff
}
// after try block, resource will close automatically
}
This works with non-memory resources such as files, streams, sockets, and database connections.
- FurrBall 13y agoPasting a response: Blocks are an improvement, but not the same as RAII. A block is literally converted to a try-finally by the compiler. It is the same thing with a cleaner syntax. There is no safety added to the old Java way. A programmer can forget to put his stuff in a block and leak the resource the same as he forgets to use a try-finally. The onus is on the consumer, not the library writer. With C++ RAII the onus is removed from the consumer. The consumer writes safe code automatically, no onus to remember any special clean up idioms.