Python has a nice feature: the "with" statement. It's useful for making global changes that affect all code called within the statement.
e.g. you could define a class CapturePrintStatements to capture all print statements called within the "with"
with CapturePrintStatements() as c:
print 'Stuff Done'
print 'More Stuff Done'
assert c.get_text() == 'Stuff Done'
Is there an equivalent in Java?
try-with-resources is its Java equivalent, and is available in Java 7 and up.
That gives you the possibility to work with resources that need to be explicitly closed, without worrying about closing them. For the example:
Before Java7:
InputStream input = null;
try {
input = new FileInputStream("myFile.txt");
} finally {
if(input != null){
input.close();
}
}
Java 7 & up:
try(FileInputStream input = new FileInputStream("myFile.txt")) {
// Do something with the InputStream
}
This is the try-with-resources construct. When the execution flow will go out of the try
block, the FileInputStream
will be closed automatically. This is due to the fact that FileInputStream
implements the AutoCloseable
interface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With