Defer in Java
In Java, there isn’t a direct equivalent to the defer keyword. However, we can achieve similar functionality using try-with-resources or finally blocks. In this example, we’ll use a finally block to ensure our file is closed after we’re done writing to it.
import java.io.*;
public class DeferExample {
public static void main(String[] args) {
// We'll use a try-with-resources to automatically close the file
try (FileWriter f = createFile("/tmp/defer.txt")) {
writeFile(f);
} catch (IOException e) {
e.printStackTrace();
}
}
private static FileWriter createFile(String path) throws IOException {
System.out.println("creating");
return new FileWriter(path);
}
private static void writeFile(FileWriter f) throws IOException {
System.out.println("writing");
f.write("data\n");
}
// In Java, we don't need a separate closeFile method due to try-with-resources
}In this Java version:
We use a
try-with-resourcesstatement to automatically close the file when we’re done with it. This is similar to thedeferfunctionality in the original example.The
createFilemethod now throws anIOExceptioninstead of usingpanic. In Java, we typically use exceptions for error handling.The
writeFilemethod also throws anIOException, which is caught in the main method.We don’t need a separate
closeFilemethod because thetry-with-resourcesstatement automatically closes theFileWriterfor us, even if an exception occurs.
Running the program will produce similar output to the original:
$ java DeferExample
creating
writingThe file is automatically closed after writing, thanks to the try-with-resources statement.
In Java, it’s considered good practice to use try-with-resources for managing resources that need to be closed, such as files, database connections, or network sockets. This ensures that resources are properly closed, even if an exception occurs during execution.