.NET Framework · Exception · Programátorská hádanka
Programátorská hádanka: ArgumentException, ArgumentNullException
Přijde vám na následujícím kódu něco divného?
[sourcecode language=“csharp“ padlinenumbers=“true“ gutter=“true“ light=“false“]
public void DoSomething(MyClass firstParameter)
{
if (firstParameter == null)
{
throw new ArgumentNullException(nameof(firstParameter), "My message.");
}
if (firstParameter.SomeProperty < 0)
{
throw new ArgumentException(nameof(firstParameter), "My other message.");
}
// do something…
}
[/sourcecode]
ArgumentException má parametry (String message, String paramName).
Jinak já osobě u ArgumentNullException používám vždy variantu pouze s parametrem paramName, protože to už říká samo osobě vše potřebné, ta message je u ArgumentNullException zbytečná.
Proč si špinit kód ArgumentNullException, když bez něj bysme dostali NullReferenceException, která nám řekne to samé (pokud nejsme prasata) ? :-)
Naopak vyhazování ArgumentNullException je hodně dobrá (docela rád bych to někomu zaved jako povinné) praktika, protože právě NullReferenceException neříká tu informaci, který objekt je null.
Proto jsem tam měl poznámku o nezpraseném kódu (viz. Law of Demeter).