Best practice for invalid arguments

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

What's the current recommended best practice for the exception to throw when
an argument is invalid? I could have sworn there was a general
InvalidArgumentException exposed by the framework, but if it's there I must
be blind. It seems like this is a common enough occurence that there would
be a pre-defined exception for it.
 
Hi Kyle

You could use the System.ArgumentException and set the message to indicate
which argument is invalid.

Ged
 
Thanks Ged. This one didn't show on the "Derived Classes" in the MSDN
documentation and I was too focused on the "Invalid" part when I browsed the
class library.
 
Kyle said:
Thanks Ged. This one didn't show on the "Derived Classes" in the MSDN
documentation and I was too focused on the "Invalid" part when I browsed the
class library.

In addition, do keep in mind the more specific exceptions that do exist,
such as IndexOutOfRangeException and InvalidOperation exception. In
some cases, these make more sense with respect to reporting a parameter
that isn't correct than simply throwing an ArgumentException.

Pete
 
Thanks Ged. This one didn't show on the "Derived Classes" in the MSDN
documentation and I was too focused on the "Invalid" part when I browsed
the
class library.

You might also consider simply "Assert"ing on invalid arguments if you
control all clients and invalid arguments are illegal in the release version
(which is my own preferred choice).
 
Back
Top