TreK
TreK

Reputation: 1174

C# What exception should be thrown when number out of range

I have a simple C# method that generates a number. If the system tries to generate a number out of the range that has been defined, I'd like to throw an exception but there are so many, I'm not sure what exception to throw?

http://msdn.microsoft.com/en-us/library/system.systemexception.aspx

An example would be a method that returns the next number available, but should not be greater than 100. If the system tries to generate a number (i.e. 101) then I want to throw an exception.

Upvotes: 2

Views: 5458

Answers (2)

ASB
ASB

Reputation: 328

The OverflowException seems to do what you're looking for:

OverflowException, which is thrown when the result of an operation is outside the bounds of the target data type. That is, it is less than a number's MinValue property or greater than its MaxValue property. For example, attempting to assign 200 + 200 to a Byte value throws an OverflowException exception, since 400 greater than 256, the upper bound of the Byte data type. https://learn.microsoft.com/en-us/dotnet/api/system.arithmeticexception?view=net-5.0

Upvotes: -1

gleng
gleng

Reputation: 6304

You're looking for ArgumentOutOfRangeException - The exception that is thrown when the value of an argument is outside the allowable range of values as defined by the invoked method. (MSDN: http://msdn.microsoft.com/en-us/library/system.argumentoutofrangeexception%28v=vs.110%29.aspx)

Upvotes: 9

Related Questions