Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

InvalidOperationException vs. ArgumentException [closed]

I know the summaries and descriptions.

But what if the ARGUMENT is in an INVALID STATE?

I think the ArgumentException is more appropriate because the InvalidOperationException documentation says that the object on what the method is called itself has to be in an invalid state. Does this make sense?

like image 234
timmkrause Avatar asked May 08 '13 07:05

timmkrause


People also ask

When should you throw an ArgumentException?

Remarks. 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.

What does system InvalidOperationException mean?

InvalidOperationException is used in cases when the failure to invoke a method is caused by reasons other than invalid arguments. Typically, it is thrown when the state of an object cannot support the method call. For example, an InvalidOperationException exception is thrown by methods such as: IEnumerator.

What is argument out of range exception?

The ArgumentOutOfRangeException exception is thrown when the argument passed to a method is not null and contains a value that is not within the set of expected values. This exception type has the properties ParamName and ActualValue which helps understand the cause of the exception.


1 Answers

The documentation says it pretty clearly:

InvalidOperationException is used in cases when the failure to invoke a method is caused by reasons other than invalid arguments.
...
If the method invocation failure is due to invalid arguments, then ArgumentException or one of its derived classes, ArgumentNullException or ArgumentOutOfRangeException, should be thrown instead.

Your method expects the arguments to be in a certain state, which could include anything including being in a "valid state" as defined by the argument type itself.
I think the main point of difference is the source of the problem:
Is it the argument or the object on which you call the method?

like image 124
Botz3000 Avatar answered Sep 21 '22 17:09

Botz3000