构造函数可以在Java中抛出异常吗? [英] Can constructors throw exceptions in Java?

查看:931
本文介绍了构造函数可以在Java中抛出异常吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

构造函数是否允许抛出异常?

Are constructors allowed to throw exceptions?

推荐答案

通常这意味着新对象立即有资格进行垃圾回收(虽然它可能不会被收集一段时间,当然)。如果它在构造函数中早期可见(例如,通过指定一个静态字段,或将自己添加到集合中),那么半构建对象可能会粘在一起。

Yes, constructors can throw exceptions. Usually this means that the new object is immediately eligible for garbage collection (although it may not be collected for some time, of course). It's possible for the "half-constructed" object to stick around though, if it's made itself visible earlier in the constructor (e.g. by assigning a static field, or adding itself to a collection).

有一件事要注意在构造函数中抛出异常:因为调用者(通常)没有办法使用新对象,构造函数应该小心避免获取非托管资源(文件句柄等)然后抛出异常而不释放它们。例如,如果构造函数尝试打开 FileInputStream FileOutputStream ,并且第一个成功,但第二个失败,您应该尝试关闭第一个流。这变得更难,如果它是一个子类构造函数抛出异常,当然...这一切都变得有点棘手。这不是一个常见的问题,但值得考虑。

One thing to be careful of about throwing exceptions in the constructor: because the caller (usually) will have no way of using the new object, the constructor ought to be careful to avoid acquiring unmanaged resources (file handles etc) and then throwing an exception without releasing them. For example, if the constructor tries to open a FileInputStream and a FileOutputStream, and the first succeeds but the second fails, you should try to close the first stream. This becomes harder if it's a subclass constructor which throws the exception, of course... it all becomes a bit tricky. It's not a problem very often, but it's worth considering.

这篇关于构造函数可以在Java中抛出异常吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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