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

查看:46
本文介绍了构造函数可以在 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天全站免登陆