Cleaning Up Resources

In many languages, including Java, safely cleaning up resources is a bit tricky if you haven’t done it before. Take reading from a file as an example: first we need to open the file resource, then do our work with it, and then when we’re finished, we need to close the resource. It’s just a three-step process, but there’s a lot that can go wrong. There might be an exception when reading from the file. There might have been an exception when opening the file. For this reason, it’s not uncommon to see Java like the following code sample to read a file’s contents into a string:

context/teardown_filestream.java
 
public​ ​String​ readFile(​String​ filePath) ​throws​ IOException {
 
FileInputStream​ fileStream = null;
 
StringBuilder ...

Get Mastering Clojure Macros now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.