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

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

问题描述

对于具有单个参数的构造函数,如果参数为空/空,则可以在构造函数内部引用ArgumentNullException吗?或者,应该在实际使用参数的方法中抛出?谢谢。

解决方案

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



始终记住Early Early Principle 。概念现在失败了,所以你不要浪费时间调试或体验意想不到的系统功能。



或者你也可以为和ArgumentNullException为null抛出一个ArgumentException。在任一情况下,请确保您抛出一个有效的异常消息。






总是一个很好的参考文章,用于管理异常:拇指的异常管理规则






关于@Steve Michelotti所说的话(因为我是CodeContracts的巨大粉丝)

  Contract.Requires< ArgumentNullException>(inputParemeter!= null,inputparameter不能为null); 
Contract.Requires< ArgumentException>(inputParemeter!=,inputparameter不能为空字符串);

  Contract.Requires< ArgumentNullException>(!string.IsNullOrEmpty(inputParemeter),inputparameter不能为null或空字符串); 


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.

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


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");

alternatively

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

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

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