Assume I have a class C that holds resources that need to be closed as member variables.
public class C {
private ClosableResource1 closableResource1;
private ClosableResource2 closableResource2;
.....
public C(){
closableResource1 = new ClosableResource1();
closableResource2 = new ClosableResource2();
.....
// some logic that can fail
}
close(){
closableResource1.close()
closableResource2.close()
.....
}
}
If the constructor succeeds I can be sure that close() will be called eventually by some entity manager and all the resources will be freed.
But how can I make sure I close the resources when the constructor fails? The failure can happen because I have additional logic in the constructor that can throw exception or I get some RuntimeException outside of my control?
Some things I though of:
- Wrapping the constructor body with a
try-catchblock. Then, assuming I have a lot of closable members I'll have to have a bigifstatement in thecatchblock checking which resources were already initializing and only close them. - Offloading the
ClosableResources creation to someinit()function. Then I would have to make sureinit()succeeded every time I try to use the object.
Is there some elegant solution? Or is this much more implementation specific then that?