当我有一个try-with-resources块时:
try (MyIOWriter miow = new MyIOWriter() /* implements AutoCloseable */)
{
miow.write("foo"); // Might throw IOException
}
catch (IOException e) // possibly executed on close or on write
{
LOG.error("MyIOWriter failed to write something", e);
}
有一个执行catch块的机会,因为AutoCloseable MyIOWriter
在其IOException
方法上抛出了close
。在这种情况下,记录器消息将是错误的。是否可以使用try-with-resources块并分别从AutoCloseable和块本身捕获异常?像这样:
try (MyIOWriter miow = new MyIOWriter() /* implements AutoCloseable */)
{
miow.write("foo"); // Might throw IOException
}
catch (IOException e) // possibly executed on write
{
LOG.error("MyIOWriter failed to write something", e);
}
finally catch (IOException e) // possibly executed on close
{
LOG.error("MyIOWriter failed to close", e);
}