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

查看:25
本文介绍了在构造函数中抛出 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.

或者,您也可以为 "" 抛出 ArgumentException,为 null 抛出 ArgumentNullException.无论哪种情况,请确保您抛出有效的异常消息.

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 Michelotti 所说的话(因为我是 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天全站免登陆