Oracle explains how try-with-resources work here
TL DR of this:
There is no easy way to do this in Java 1.6. The problem is the absence of a forbidden field in Exception. You can either ignore this or hard code, which happens when both try parameters close different exceptions or create your own Exception hierarchy that has a suppressed field.
In the second case, the link above gives the correct way to do this:
AutoClose autoClose = new AutoClose(); MyException myException = null; try { autoClose.work(); } catch (MyException e) { myException = e; throw e; } finally { if (myException != null) { try { autoClose.close(); } catch (Throwable t) { myException.addSuppressed(t); } } else { autoClose.close(); } }
equivalently
try (AutoClose autoClose = new AutoClose()) { autoClose.work(); }
If you want to make it simpler and not create many new Exception classes, you have to decide what to do in catch at the end of finally (t or e).
PS. Working with multiple variable declarations in try is also discussed in the link above. And the amount of code you need for this is overwhelming. Most people use shortcuts in Java 1.6, not handling exceptions in the finally block and using nullchecks.
source share