Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should an IllegalArgumentException be thrown?

I'm worried that this is a runtime exception 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 that seems like it would force the following design:

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

To get it back to being a checked exception.

Okay, but let's go with that. If you give bad input, you get a runtime error. So firstly that's actually a fairly difficult policy to implement uniformly, because you could have to do the very 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 - while checking 0 <= pct && pct <= 100 the client code could be expected to do statically, this is not so for more advanced data such as an email address, or worse, something that has to be checked against a database, therefore in general client code cannot pre-validate.

So basically what I'm saying is I don't see a meaningful consistent policy for the use of IllegalArgumentException. It seems it should not be used and we should stick to our own checked exceptions. What is a good use case to throw this?

like image 294
djechlin Avatar asked Mar 04 '13 18:03

djechlin


People also ask

When should you throw IllegalStateException?

The IllegalStateException is thrown when the Java environment or application is not in an appropriate state for the requested operation. This can occur when dealing with threads or the Collections framework of the java. util package under specific conditions.

What causes IllegalArgumentException?

IllegalArgumentException CauseWhen a method is passed illegal or unsuitable arguments, an IllegalArgumentException is thrown.

What causes IllegalArgumentException in Java?

This exception is thrown in order to indicate that a method has been passed an illegal or inappropriate argument. For example, if a method requires a non-empty string as a parameter and the input string equals null, the IllegalArgumentException is thrown to indicate that the input parameter cannot be null.

How do you handle IllegalArgumentException?

You should not handle an IllegalArgumentException. It's porpose is to inform the developer, that he have called a method with wrong arguments. Solution is, to call the method with other arguments. Unless the library which throws it needs to reexamine the exception at a higher level before it exits upward to the caller.


2 Answers

The API doc for IllegalArgumentException:

Thrown to indicate that a method has been passed an illegal or inappropriate argument.

From looking at how it is used in the JDK libraries, I would say:

  • It seems like a defensive measure to complain about obviously bad input before the input can get into the works and cause something to fail halfway through with a nonsensical error message.

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

I would use IllegalArgumentException to do last ditch defensive argument checking for common utilities (trying to stay consistent with the JDK usage). Or where the expectation is that a bad argument is a programmer error, similar to an NullPointerException. I wouldn't use it to implement validation in business code. I certainly wouldn't use it for the email example.

like image 101
Nathan Hughes Avatar answered Oct 05 '22 18:10

Nathan Hughes


When talking about "bad input", you should consider where the input is coming from.

Is the input entered by a user or another external system you don't control, you should expect the input to be invalid, and always validate it. It's perfectly ok to throw a checked exception in this case. Your application should 'recover' from this exception by providing an error message to the user.

If the input originates from your own system, e.g. your database, or some other parts of your application, you should be able to rely on it to be valid (it should have been validated before it got there). In this case it's perfectly ok to throw an unchecked exception like an IllegalArgumentException, which should not be caught (in general you should never catch unchecked exceptions). It is a programmer's error that the invalid value got there in the first place ;) You need to fix it.

like image 25
Tom Avatar answered Oct 05 '22 16:10

Tom