简体   繁体   中英

Throwing ArgumentNullException

Is it a good idea to throw ArgumentNullException() when having a null value? This thread doesn't mention the most obvious exception to throw on a null.

Thanks

ArgumentNullException should only be used when the parameter to a method is found to be null:

public void MyMethod(MyClass cannotBeNull)
{
    if (cannotBeNull == null)
    {
        throw new ArgumentNullException("cannotBeNull");
    }
    // Do something useful
}

Actually you are reading it backwards, the other scenerio posses the situation:

If I am expecting a null value and get a defined value

If you look at the MSDN: ArgumentNullException it is specifically for

The exception that is thrown when a null reference (Nothing in Visual Basic) is passed to a method that does not accept it as a valid argument.

I am expecting a null and I get something

vs.

I am expecting something and I get null

That said, there is no reason you can not, or should not, create your own

public class IWantANullException:Exception 

and throw it around in what ever way you wish.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM