When should an IllegalArgumentException be thrown?

I am worried that this is an exception at runtime, so it should probably be used sparingly. Standard use case:

void setPercentage(int pct) { if( pct < 0 || pct > 100) { throw new IllegalArgumentException("bad percent"); } } 

But it looks like this would force the following design:

 public void computeScore() throws MyPackageException { try { setPercentage(userInputPercent); } catch(IllegalArgumentException exc){ throw new MyPackageException(exc); } } 

To return to checking the exception.

Ok, but let it go. If you give bad input, you get a runtime error. So, firstly, it is actually a rather complicated policy to implement evenly, because you may need to do the exact opposite conversion:

 public void scanEmail(String emailStr, InputStream mime) { try { EmailAddress parsedAddress = EmailUtil.parse(emailStr); } catch(ParseException exc){ throw new IllegalArgumentException("bad email", exc); } } 

And worse - when checking 0 <= pct && pct <= 100 you can expect the client code to do statically, this is not the case for more advanced data, such as an email address or, even worse, something that needs to be checked in the database, so the client’s common code cannot be pre-checked.

So basically what I am saying, I do not see a meaningful consistent policy of using IllegalArgumentException . It does not seem to be used, and we must adhere to our own checked exceptions. What could be useful for this?

+62
java exception illegalargumentexception
Mar 04 '13 at 18:34
source share
5 answers

Api doc for IllegalArgumentException exception:

Thrown to indicate that the method was passed with an illegal or inappropriate argument.

From a look at how it is used in jdk libraries , I would say:

  • It seems that the protective measure complains about a clearly bad input before the input can get into work and cause something to fail halfway through a meaningless error message.

  • It is used for cases where it would be too annoying to throw a checked exception (although it appears in the java.lang.reflect code, where the concern about the ridiculous levels of the checked exception-exception is not otherwise obvious).

I would use the IllegalArgumentException method to execute the last-ditch protective argument - to check for common utilities (try to stay consistent with jdk), where the expectation is that a bad argument is a programmer error similar to NPE. I would not use it to implement validation in business code. Of course, I would not use it as an example of email.

+49
Mar 04 '13 at 19:48
source share

Speaking of “bad input,” you have to consider where the input comes from.

An input entered by a user or other external system that you do not control, you should expect the input to be invalid and always check it. In this case, it is normal to throw a checked exception. Your application should "recover" from this exception by providing the user with an error message.

If the input comes from your own system, such as your database or some other parts of your application, you should be able to rely on it to be valid (it must be checked before it arrives). In this case, it is normal to throw an exception, such as an IllegalArgumentException, which should not be caught (in general, you should never catch unchecked exceptions). The programmer’s mistake is that the invalid value came first;) You need to fix it.

+17
Mar 04 '13 at 20:06
source share

Throwing runtime exceptions “sparingly” is not really a good policy. Effective Java recommends using checked exceptions when the caller can reasonably expect recovery. (A programmer’s error is a concrete example: if a particular case indicates a programmer’s error, then you should throw an exception, you want the programmer to have a stack trace where a logical problem has occurred, and not try to deal with it yourself.)

If there is no hope of recovery, feel free to use the excluded exceptions; it makes no sense to catch them, so great.

It is not 100% clear from your example which case this example is in your code.

+9
Mar 04 '13 at 18:40
source share

As stated in the official oracle manual, it states that:

If it is reasonable to expect the client to recover from the exception, make it a verified exception. If the client cannot do anything to recover from the exception, make it an unchecked exception.

If I have an application interacting with a database using JDBC , and I have a method that takes an argument as an int item and double price . The price element for the corresponding element is read from the database table. I simply multiply the total number of item purchased with the price value and return the result. Although I am always sure at the end (end of the application) that the value of the price field in the table can never be negative. But what if the price value goes negative ? This shows that there is a serious problem with the database. Perhaps the operator entered the price incorrectly. This is the problem that the other part of the application calling this method cannot wait and cannot recover from it. This is a BUG in your database. So, an IllegalArguementException() should also be thrown in this case to indicate that the price can't be negative .
I hope that I have clearly stated my point of view.

+4
Mar 04 '13 at 19:06
source share

Any API must verify the validity of each parameter of any public method before executing it:

 void setPercentage(int pct, AnObject object) { if( pct < 0 || pct > 100) { throw new IllegalArgumentException("pct has an invalid value"); } if (object == null) { throw new IllegalArgumentException("object is null"); } } 

They represent 99.9% of cases of errors in the application because they request impossible operations, so in the end they are errors that should lead to the failure of the application (so this is an unrecoverable error).

In this case, and with a quick approach to failure, you must let the application terminate so as not to damage the state of the application.

+4
Dec 17 '15 at 11:47
source share



All Articles