访问在 catch 子句中声明的 "try-with"-资源
Access declared "try-with"-resource in catch-clause
我有一个名为 "VirtuellTx" 的可自动关闭的 class。它是一种特殊的交易,支持 "commit()"- 和 "rollback()"- 方法。如何访问 catch 块中声明的 "VirtuellTx"-资源以执行回滚 ()?
try (VirtuellTx lVtx = new VirtuellTx()) {
// do something ...
lVtx.commit();
} catch (Exception e) {
lVtx.rollback();
}
catch 块无法访问 lVtx:"lVtx cannot be resolved"
资源仅在 try-with-resources 语句块内的范围内。 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.
将catch
移到里面:
try (VirtuellTx lVtx = new VirtuellTx()) {
try {
// do something ...
lVTX.commit();
} catch (Exception e) {
lVtx.rollback();
}
}
我有一个名为 "VirtuellTx" 的可自动关闭的 class。它是一种特殊的交易,支持 "commit()"- 和 "rollback()"- 方法。如何访问 catch 块中声明的 "VirtuellTx"-资源以执行回滚 ()?
try (VirtuellTx lVtx = new VirtuellTx()) {
// do something ...
lVtx.commit();
} catch (Exception e) {
lVtx.rollback();
}
catch 块无法访问 lVtx:"lVtx cannot be resolved"
资源仅在 try-with-resources 语句块内的范围内。 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.
将catch
移到里面:
try (VirtuellTx lVtx = new VirtuellTx()) {
try {
// do something ...
lVTX.commit();
} catch (Exception e) {
lVtx.rollback();
}
}