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

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

问题描述

什么时候是构造函数抛出异常的正确? (或者在Objective C的情况下:init是什么时候返回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天全站免登陆