Naughty ArgumentException

Writing a function you probably write following checks as a reflex:

void DoSomething(string argument) {
if (argument == null) {
throw new ArgumentNullException("argument", "No nulls allowed!");
}
if (argument == string.Empty) {
throw new ArgumentOutOfRangeException("argument", "No empty strings!");
}
if (Environment.Foo && (argument == "bar")) {
throw new ArgumentException("argument", "Something else!");
}
...
}

Yep, there is an error in third "throwing". For some unknown reason ArgumentException needs parameters in a different order. Correct statement would be:

    ...
throw new ArgumentException("Something else!", "argument");
...
}

What will happen if you mess it up?

Well, nothing much. Exception will still be thrown and your code should be fine. You will see wrong exception text but any stacktrace will probably lead you to correct spot in code.

But it looks ugly.

Leave a Reply

Your email address will not be published. Required fields are marked *