views:

206

answers:

4

Hello. This question might sound a bit stupid but here it goes.

I have two functions that can be called at any moment. The first function takes a snapshot, and the second one analyses the data taken from that snapshot. Of course if the user tries to analyse the snapshot before taking it, my application should throw an exception. I know the ArgumentOutOfRangeException that is generally thrown when......there is an invalid argument, but that is not really the case. Is there any in-built exception for this kind of cases, or will I have to use ArgumentOutOfRangeException?

Thanks

+16  A: 

InvalidOperationException?

LukeH
"The exception that is thrown when a method call is invalid for the object's current state."
280Z28
+16  A: 

Sounds like an InvalidOperationException. http://msdn.microsoft.com/en-us/library/system.invalidoperationexception.aspx

That said, if you can design your API so that you can't get in this situation, that would be better. Something like (pseudo):

public Data TakeSnapshot()
{
   // ...
   return new Data(...);
}

public void Analyze(Data data)
{
   // ...
}

Like this, there's no way to call them out of order.

Kim Gräsman
Good idea. You may even be able to make `Analyze` `static` so that it is completely disconnected from state.
Fredrik Mörk
A: 

I would use System.ArgumentException - The exception that is thrown when one of the arguments provided to a method is not valid.

Tomas Pajonk
+8  A: 

Why do you allow him to get it wrong? How about a method

 ISnapshot getSnapshot()

with ISnapshot having the analyze method. Or just analyze() which gets the snapshot if one isn't available

djna
+1, I would go for this approach, make the problem disappear by requiring the code to actually have the snapshot before access to the method is given.
Lasse V. Karlsen
I do get your point, but maybe in this case is not appropriate.
devoured elysium
... not appropriate because?
djna