Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should Guid.Empty Result in ArgumentException or ArgumentOutOfRangeException

Tags:

.net

oop

api

Imagine that you have a method with the following signature:

public void DoSomething(Guid id)

If Guid.Emtpy represents an illegal value, which Exception type would it be most appropriate to throw? ArgumentException or ArgumentOutOfRangeException?

I'm leaning slightly towards ArgumentException, since I don't think that all Guids except Guid.Empty is much of a range - it's a bit too inclusive: There is only one excluded member.

However, I am in no way determined that this should be the case, so I'd like to hear if anyone can provide arguments for one or the other?

I'm well aware that this is mainly a semantic discussion, but in the interest of good API design I'd still like to know whether there are clear cases for one or the other option.

like image 880
Mark Seemann Avatar asked Jun 22 '09 11:06

Mark Seemann


People also ask

When should you throw an ArgumentException?

ArgumentException is thrown when a method is invoked and at least one of the passed arguments does not meet the parameter specification of the called method. The ParamName property identifies the invalid argument.

How do you handle system ArgumentOutOfRangeException?

If the string is empty, as the final string passed to the method is, the method throws an ArgumentOutOfRangeException exception. You can eliminate the exception by testing whether the string's String. Length is greater than zero or by calling the IsNullOrEmpty method to ensure that the string is not null or empty.

How do you handle Argumentnullexception in C#?

To prevent the error, instantiate the object. An object returned from a method call is then passed as an argument to a second method, but the value of the original returned object is null . To prevent the error, check for a return value that is null and call the second method only if the return value is not null .


1 Answers

I'd throw an ArgumentException. Its docs say:

The exception that is thrown when one of the arguments provided to a method is not valid.

which is exactly the scenario you describe. You want something along the lines of:

throw new ArgumentException("Guid.Empty is not a valid id", "id");
like image 179
adrianbanks Avatar answered Oct 25 '22 08:10

adrianbanks