抛出ArgumentNullException在构造函数? [英] Throwing ArgumentNullException in constructor?

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

问题描述

对于单参数的构造函数,它是确定以抛出一个ArgumentNullException该构造函数中,如果参数为空/空的?或者,它应该在实际使用参数的方法抛出?谢谢你。

For a constructor with a single parameter, is it OK to throw an ArgumentNullException inside the constructor if the parameter is null/empty? OR, should it be thrown in the method that actually uses the argument? Thanks.

推荐答案

是的,如果它是完全必要的,然后抛出异常。你不应该*后抛出异常。

Yes, if it is completely essential then throw the exception. You should not* throw the exception later.

时刻牢记故障早期原理。现在的概念存在失败了,所以你不要浪费时间调试或经验意外的系统功能。

Always remember the "Fail Early Principle". Concept being fail now, so you don't waste time debugging or experience unexpected system functionality.

另外,您也可以抛出,和为ArgumentNullException一个空的ArgumentException。在这两种情况下,确保你扔一个有效的异常信息。

Alternatively you could also throw a ArgumentException for "" and ArgumentNullException for null. In either case make sure you throw a valid Exception message.

始终用于管理例外一个很好的参考文章:

Always a good reference article for managing exceptions: Good Exception Management Rules of Thumb

这是什么@Steve米凯洛蒂说附注(因为我的codeContracts一个巨大的风扇)

Side note on what @Steve Michelotti said (because i am a huge fan of CodeContracts)

Contract.Requires<ArgumentNullException>(inputParemeter!= null, "inputparameter cannot be null");
Contract.Requires<ArgumentException>(inputParemeter!= "", "inputparameter cannot be empty string");

或者

Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(inputParemeter), "inputparameter cannot be null or empty string");

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

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