从构造函数中抛出异常 [英] throwing exception from constructor

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

问题描述

从构造函数中抛出异常是否合适?


这是我能想到的唯一方法来表示

构造函数的失败,其中我我正在调用其他几个类来对象进行初始化。


TIA

Sek

Is it appropriate to throw exception from a constructor?

Thats the only way i could think of to denote the failure of
constructor, wherein i am invoking couple of other classes to
initialise the object.

TIA
Sek

推荐答案

据我所知,这不是从

构造函数中抛出异常的合适方法。

如果您确定发生异常时,您应该处理所有资源,例如,文件处理程序,内存等。


Sek ??????
As far as i know, It''s not a appropriate way to throw exception from a
constructor.
If you can make sure that when exception occured, you should dispose
all resoures, such as, File handler, memory, etc.

Sek ???é?????

从构造函数中抛出异常是否合适?


这是唯一的我可以想到的方式来表示

构造函数的失败,其中我调用了几个其他类来初始化对象。


TIA

Sek
Is it appropriate to throw exception from a constructor?

Thats the only way i could think of to denote the failure of
constructor, wherein i am invoking couple of other classes to
initialise the object.

TIA
Sek


Sek写道:
Sek wrote:

是否适合从构造函数中抛出异常?


这是我能想到的唯一表达方式

构造函数的失败,其中我调用了几个其他类来使用
初始化对象。
Is it appropriate to throw exception from a constructor?

Thats the only way i could think of to denote the failure of
constructor, wherein i am invoking couple of other classes to
initialise the object.



是的,没关系,没关系。有几种框架类型可以做到。例如,请参阅

Guid(字符串),FileStream构造函数和String(char [],int,

int)。


Jon

Yup, that''s fine. Several framework types do it. For examples, see
Guid(string), the FileStream constructors, and String(char[], int,
int).

Jon


simida写道:
simida wrote:

据我所知,它'不是从

构造函数中抛出异常的合适方法。
As far as i know, It''s not a appropriate way to throw exception from a
constructor.



它已经广泛使用,并且没有理由不在.NET中这样做。在

非托管C ++中,有一些原因让它成为一个坏主意,但它们并不适用于.NET。

It''s widely done, and there''s no reason not to do it in .NET. In
unmanaged C++ there are reasons why it''s a bad idea, but they don''t
apply to .NET.


如果你能确保在发生异常时,你应该处理所有资源,例如,文件处理程序,内存等。
If you can make sure that when exception occured, you should dispose
all resoures, such as, File handler, memory, etc.



文件句柄等,是的 - 但是垃圾收集器会自动清理内存。


Jon

File handles etc, yes - but memory will automatically be cleaned up by
the garbage collector.

Jon


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

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