InvalidParameterException or IllegalArgumentException

There is already an exception to throw when you expect parameters to not be null: NullPointerException. Some programmers thinks that only faulty code throws NullPointerException, but if you really expect the parameters to not be null, and you can't recover from this situation, that's the right exception to throw. From the JavaDoc:

Thrown when an application attempts to use null in a case where an object is required.

But if we are not talking about null values, but just an invalid value, then you should throw IllegalArgumentException. From the JavaDoc:

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

As a general suggestion, I would say that you should get familiar with the Java exceptions (from java.lang package), and use them appropriately. If you don't find a suitable exception, then extend one.

Also note that the exception "InvalidParameterException" is in the package "java.security", which is probably not what you want.


First thanks for your question. Now I know about existence of InvalidParameterException. This exception belongs to package java.security and according to its javadoc

 * This exception, designed for use by the JCA/JCE engine classes, 
 * is thrown when an invalid parameter is passed 
 * to a method.

IllegalArgumentException belongs to java.lang and therefore can be used for any purpose.

I believe that in 99.9% of cases you should use IllegalArgumentException and use InvalidParameterException only in security context.


There's no apparent need to subclass those exceptions, I'd use them right away to signal, that a method has been called with illegal arguments. I'd always describe the real cause in the exceptions message part.

java.security.InvalidParameterException is already a subclass of IllegalArgumentException designed for use by the JCA/JCE engine classes (JavaDoc) and I wouldn't use or subclass it in a different context.

Tags:

C#

Java

Exception