分别处理从try-with-resources块中的close方法的AutoCloseable方法引发的IOException

时间:2019-04-29 06:58:39

标签: java exception try-with-resources

当我有一个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);
}

0 个答案:

没有答案