InvalidParameterException or IllegalArgumentException
In Java when should you throw IllegalArgumentException
and when InvalidParameterException
?
Coming from a C# background we would have an ArgumentNullException
that derived from ArgumentException
. If I would want to implement a equivalent ArgumentNullException
/Par开发者_如何转开发ameterNullException
in Java should I extend IllegalArgumentException
or InvalidParameterException
?
Note: I'm not trying to implement a ArgumentNullException
/ParameterNullException
this would just provide me with a better understanding if I could match up these with the C# framework.
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.
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 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.
精彩评论