构造函数什么时候抛出异常合适? [英] When is it right for a constructor to throw an exception?

查看:29
本文介绍了构造函数什么时候抛出异常合适?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

构造函数什么时候抛出异常合适?(或者在 Objective C 的情况下:init'er 什么时候返回 nil 才是正确的?)

When is it right for a constructor to throw an exception? (Or in the case of Objective C: when is it right for an init'er to return nil?)

在我看来,如果对象不完整,构造函数应该会失败——因此拒绝创建对象.即,构造函数应该与其调用者签订合同,以提供可以有意义地调用哪些方法的功能和工作对象?这合理吗?

It seems to me that a constructor should fail -- and thus refuse to create an object -- if the object isn't complete. I.e., the constructor should have a contract with its caller to provide a functional and working object on which methods can be called meaningfully? Is that reasonable?

推荐答案

构造函数的工作是使对象进入可用状态.在这方面基本上有两种思想流派.

The constructor's job is to bring the object into a usable state. There are basically two schools of thought on this.

一组赞成两阶段建设.构造函数只是将对象带入休眠状态,在这种状态下它拒绝做任何工作.还有一个额外的函数可以进行实际的初始化.

One group favors two-stage construction. The constructor merely brings the object into a sleeper state in which it refuses to do any work. There's an additional function that does the actual initialization.

我一直不明白这种方法背后的原因.我坚定地支持一阶段构造,其中对象在构造后完全初始化并可用.

I've never understood the reasoning behind this approach. I'm firmly in the group that supports one-stage construction, where the object is fully initialized and usable after construction.

如果单阶段构造函数未能完全初始化对象,则应该抛出.如果对象不能初始化,就一定不允许存在,所以构造函数必须抛出.

One-stage constructors should throw if they fail to fully initialize the object. If the object cannot be initialized, it must not be allowed to exist, so the constructor must throw.

这篇关于构造函数什么时候抛出异常合适?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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