devoured elysium
devoured elysium

Reputation: 105077

What kind of exception to throw?

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

Upvotes: 3

Views: 532

Answers (4)

djna
djna

Reputation: 55907

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

Upvotes: 8

Tomas Pajonk
Tomas Pajonk

Reputation: 5202

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

Upvotes: 0

Kim Gräsman
Kim Gräsman

Reputation: 7586

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.

Upvotes: 16

LukeH
LukeH

Reputation: 269388

InvalidOperationException?

Upvotes: 16

Related Questions