A resource leak occurs when an acquired resource remains unreleased after it is no longer needed. An open file handle can survive an exception, consuming one of the operating system’s limited file slots. section 15.1
Resource-safe code should:
- Close file handles as soon as they are no longer needed, including after exceptional termination. section 15.1
- Avoid reading from resources after they have been closed. section 15.1
- Apply the same discipline to network sockets and database connections. section 15.1
Exception-safe file processing
An imperative line-counting program opens a file, processes its iterator, and closes the source in a finally block. Omitting that finally block, or closing the file afterward, can leak the handle when processing raises an exception. section 15.1


