Correct exception for an empty\null string passed to a constructor
.net, c#, constructor, exception
Solution
I suppose the most correct implementation would be this:
if (bar == null) { throw new ArgumentNullException (...); }
else if (bar.Trim() == "") { throw new ArgumentException (...); }
but we might be straining a gnat and swallowing a camel. It's probably not terribly important.
On the other hand, you could build the `StringNullOrEmptyException` class.
Problem
I have a class: ``` class Foo { public Foo(string bar) { if (string.IsNullOrEmpty(bar)) throw new Exception("bar must not be null or empty."); } } ``` What is the most correct exception type to throw? Viable candidates are: - `ArgumentNullException` - `ArgumentException` - `InvalidOperationException` - `TypeInitializationException` (not this as per dasblinkenlight below) My instinct is to go with `InvalidOperationException`, as the caller is attempting to construct the object in a illegal state, though `ArgumentException` has merits as well. I wish there was a `StringNullOrEmptyException`, wouldn't that be great? Edit Thanks for the suggested question, it is similar, but I was asking specifically about it happening in the constructor and whether that would change the recommendation at all.