它是有意义的AutoCloseable的抛出一个异常接近的方法?应如何处理? [英] Is it meaningful for AutoCloseable's close method to throw an exception? How should this be handled?

查看:154
本文介绍了它是有意义的AutoCloseable的抛出一个异常接近的方法?应如何处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,这是认为坏的实践抛出异常的处置的IDisposable

In C#, it is considered bad practice to throw exceptions in the Dispose method of an IDisposable.

相比之下,Java中的<$的方法C $ C> AutoCloseable 法>允许任何抛出任何异常,并强制调用者以某种方式处理它。但什么是来电者合理预期做,如果出现这种情况?这表明,尝试关闭资源以某种方式失败。所以没有用户已尝试在继续之前再次关闭资源,或许与某种指数回退的?

By contrast, in java the close method of AutoCloseable allows any Exception whatsoever to be thrown and forces the caller to handle it somehow. But what is the caller reasonably expected to do if this happens? This suggests that the attempt to close the resource failed somehow. So does the user have to try to close the resource again before continuing, perhaps with some sort of exponential backoff?

推荐答案

看起来像涉及资源,包括隐含的close()调用每一个操作,被认为是在try {}块的一部分。甚至认为技术上/语法,资源外{}括号提及。

It looks like every operation involving the resources, including the implicit close() invocation, is considered part of the try{} block. Even thought technically/syntactically, the resources are mentioned outside the {} braces.

这意味着,如果一个IOException被关闭()时抛出,将获得一些抓赶上()子句与尝试联系(否则会向上传播)

Meaning that if an IOException gets thrown during the close(), it will get caught by some catch() clause associated with your try (or it will propagate up).

关于的原因的原因异常可能需要抛出:关闭()可能会导致flush(),同花顺()可能导致的write()s和写()■可能会失败。

About the reason why exceptions might need to be thrown : close() might cause flush(), flush() might cause write()s, and write()s might fail.

这篇关于它是有意义的AutoCloseable的抛出一个异常接近的方法?应如何处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆