我有一个名为“ VirtuellTx”的可自动关闭的类。它是一种特殊的事务,并支持“ commit()”和“ rollback()”方法。如何访问catch块中声明的“ VirtuellTx”资源以执行rollback()?
try (VirtuellTx lVtx = new VirtuellTx()) {
// do something ...
lVtx.commit();
} catch (Exception e) {
lVtx.rollback();
}
catch块无法访问lVtx:“ lVtx无法解析”
答案 0 :(得分:4)
资源仅在try-with-resources语句块的范围内。 JLS says:
在try-with-resources语句(第14.20.3节)的ResourceSpecification中声明的变量的作用域是从声明开始,到ResourceSpecification的其余部分以及与try-with-resources相关联的整个try块。声明。
将catch
移到内部:
try (VirtuellTx lVtx = new VirtuellTx()) {
try {
// do something ...
lVTX.commit();
} catch (Exception e) {
lVtx.rollback();
}
}
答案 1 :(得分:-1)
我已经对自己的工作进行了测试,可以使用多种方法,请检查哪种方法适合您的要求。我找到了很好的参考资料,并举例说明了该问题, 参考链接:http://tutorials.jenkov.com/java-exception-handling/try-with-resources.html
public class AutoClosableResource implements AutoCloseable {
private String name = null;
private boolean throwExceptionOnClose = false;
public AutoClosableResource(String name, boolean throwExceptionOnClose) {
this.name = name;
this.throwExceptionOnClose = throwExceptionOnClose;
}
public void doOp(boolean throwException) throws Exception {
System.out.println("Resource " + this.name + " doing operation");
if(throwException) {
throw new Exception("Error when calling doOp() on resource " + this.name);
}
}
@Override
public void close() throws Exception {
System.out.println("Resource " + this.name + " close() called");
if(this.throwExceptionOnClose){
throw new Exception("Error when trying to close resource " + this.name);
}
}}
另一种方法
public static void tryWithResourcesSingleResource() throws Exception {
try(AutoClosableResource resourceOne = new AutoClosableResource("One", true)) {
resourceOne.doOp(false);
} catch(Exception e) {
Throwable[] suppressed = e.getSuppressed();
throw e;
} finally {
throw new Exception("Hey, an exception from the finally block");
}}