Is there something like Python with context manager in Java?
For example say I want to do something like the following:
getItem(itemID){
Connection c = C.getConnection();
c.open();
try{
Item i = c.query(itemID);
}catch(ALLBunchOfErrors){
c.close();
}
c.close();
return c;
}
where in python I just have:
with( C.getConnection().open() as c):
Item i = c.query(itemID);
return i;
Not at the moment; Java still hasn’t added syntactic sugar for this pattern. Still, it won’t get as clean as
with(Python) orusing(C#), but you can at least clean that up a little bit by just having one call toc.close()inside afinallyblock, instead of twice as you’ve done:This also brings it in line with how both
withandusingare actually implemented, which is atry..finallyblock (not atry..catch).