18

Should you throw an exception if a method's input values are out of range? eg

//no imaginary numbers
public int MySquareRoot(int x)
{
    if (x<0)
    {
    throw new ArgumentOutOfBoundsException("Must be a non-negative integer"); 
    }

    //our implementation here 

}

Now this method should never be called with a non-negative number, but hey programmers make mistakes. Is throwing exceptions here the right thing to do?

dwjohnston
  • 2,553
  • 6
    If the language supports it (ie: c#), you can use uint – RMalke May 13 '14 at 12:23
  • 1
    Would an IllegalArgumentException be sufficent here? – Robert Niestroj May 13 '14 at 13:18
  • @eklam, then you still have to check for the upper bound – Sebastian Godelet May 13 '14 at 13:38
  • 4
    throw new QuestionTooVagueException("Specify a language when asking questions about best practices."); – Caleb May 13 '14 at 17:52
  • The question of whether one should throw an exception or not should be language agnostic. – Salsero69 May 15 '14 at 14:51