投掷ArgumentNullException [英] Throwing ArgumentNullException

查看:108
本文介绍了投掷ArgumentNullException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有需要某种类型的对象作为参数的方法。现在说,如果此方法传递null参数,这是一个致命的错误,一个异常应该被抛出。它是值得的,我的代码是这样的(记住,这是一个简单的例子):

Suppose I have a method that takes an object of some kind as an argument. Now say that if this method is passed a null argument, it's a fatal error and an exception should be thrown. Is it worth it for me to code something like this (keeping in mind this is a trivial example):

void someMethod(SomeClass x)
{
    if (x == null){
        throw new ArgumentNullException("someMethod received a null argument!");
    }

    x.doSomething();
}



抑或是安全的,我只依靠它扔NullException时,它调用x.doSomething()?

Or is it safe for me to just rely on it throwing NullException when it calls x.doSomething()?

其次,假设的someMethod是一个构造函数和x将不被使用,直到另一种方法被调用。我应该马上抛出异常或等待需要点¯x,直到和抛出异常呢?

Secondly, suppose that someMethod is a constructor and x won't be used until another method is called. Should I throw the exception immediately or wait until x is needed and throw the exception then?

推荐答案

我喜欢 ArgumentNullException 的NullReferenceException 不是检查参数将提供。一般情况下,我的选择是试图调用一个潜在的空对象的方法之前,请务必检查无效。

I prefer the ArgumentNullException over the NullReferenceException that not checking the argument would provide. In general, my preference is to always check for nullity before trying to invoke a method on a potentially null object.

如果该方法是一个构造,那么这将取决于几个不同的因素:是否有同样的财产公开setter和它是如何可能的对象实际被使用。如果有一个公共的setter,那么不通过构造提供了一个有效的实例是合理的,不应该导致异常。

If the method is a constructor, then it would depend on a couple of different factors: is there also a public setter for the property and how likely is it that the object will actually be used. If there is a public setter, then not providing a valid instance via the constructor would be reasonable and should not result in an exception.

和如果没有公共的setter它可以使用包含对象不参照注入的对象,你可能要推迟检查/异常,直到它的使用尝试。我认为,一般情况下,虽然,将是注入的对象是该实例的运作至关重要,因此一个ArgumentNull例外是完全合理的,因为实例不能没有它。

If there is no public setter and it is possible to to use the containing object without reference to the injected object, you may want to defer the checking/exception until its use is attempted. I would think that the general case, though, would be that injected object is essential to the functioning of the instance and thus an ArgumentNull exception is perfectly reasonable since the instance can't function without it.

这篇关于投掷ArgumentNullException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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