Search code examples
javatry-with-resources

Access declared "try-with"-resource in catch-clause


I have an autoclosable class named "VirtuellTx". It is a special kind of transaction and supports a "commit()"- and "rollback()"-Method. How can I access the declared "VirtuellTx"-resource in the catch-block to perform a rollback()?

try (VirtuellTx lVtx = new VirtuellTx()) {
    // do something ...
    lVtx.commit();
} catch (Exception e) {
    lVtx.rollback();
}

The catch-block can not access lVtx: "lVtx cannot be resolved"


Solution

  • Resources are only in scope inside the block of the try-with-resources statement. JLS says:

    The scope of a variable declared in the ResourceSpecification of a try-with-resources statement (§14.20.3) is from the declaration rightward over the remainder of the ResourceSpecification and the entire try block associated with the try-with-resources statement.

    Move the catch inside:

    try (VirtuellTx lVtx = new VirtuellTx()) {
      try {
        // do something ...
        lVTX.commit();
      } catch (Exception e) {
        lVtx.rollback();
      }
    }