What is advisable to defer the checking an IllegalArgumentException?

Consider an example, of adding two hex numbers represented as char array: eg: 2A and 1D.

Now, A upto F are valid, but G-Z are invalid for 16 bits. I have two cases below to throw IllegalArguments, in case 1 it is thrown at the begining, before even additon can begin. In second example it occurs when additon is in progress.

Please do not suggest changes to the code snippet, Its tailor made to ask my question. The question being - is it better practice/ common practice to throw IllegalArgument during the algorith m ( in this case addition ) rather than upfront ?

Case 1:

  1. If char1.length == 0, or char2.length == 0 throw illegalargument.
  2. Check each char in char1, if any char is illegal then throw illegalargs.
  3. Check each char in char2, if any char is illegal then throw illegalargs.

Cons of case 2: Extra for loop to check each char in char arrays. O(n)

Case 2:

  1. If char1.length == 0, or char2.length == 0 throw illegalargument.

 for (; j >= 0; j--, i--) {
            int num1Digit = Character.digit(longNum.charAt(i), radix);
            if (num1Digit == -1) throw new IllegalArgumentException("Invalid radix for character"); // eg: 1Z, and radix is 16.
            int num2Digit = Character.digit(shortNum.charAt(j), radix);
            if (num2Digit == -1) throw new IllegalArgumentException("Invalid radix for character"); // eg: 1Z, and radix is 16.

Here illegal argument is thrown when actual addition is in progress.

Jon Skeet
people
quotationmark

In this case, there's no real harm done in terms of the behaviour due to checking later - it's not like the code which has executed so far in the method will have had an observable impact. You'll have wasted a small amount of time, but really that's negligible in the situation where you're throwing an exception anyway.

You definitely want to avoid (wherever possible, anyway) the situation where invalid input is only detected half way through an operation and the work you've done so far is already visible. That makes it much harder to recover from errors.

Personally, I prefer to have as much of the validation at the start of the method as possible - that way it's clear from the code itself what the expectations are, and the "work" of the code can all be put together, assuming valid input (as it happens after validation).

Sometimes, however, you'll only know whether something's valid when you've already done some work - it's annoying when that happens, but it's sometimes unavoidable. Just try to make that early work "local" (no side-effects) if possible.

people

See more on this question at Stackoverflow