How to access a try-with-resource variable outside the bock?

  • A+
Category:Languages

Why can't I assign a try-with-resource variable outside of the try block?

The following statement is invalid:

Connection con = null; try (con = DatabaseService.getConnection()) { //this is invalid. why?      con.execute(...); } catch (Exception e) {     con.rollback(); } 

How can I get access to the con variable inside the catch block?


I'd design it like this:

try (Connection con = DatabaseService.getConnection()) {     try {         con.execute(...);     } catch (Exception e) {         con.rollback();     } } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: