Java Beginner: What to use with wrong length vector passed as argument
If I'm having a function that does element wise addition. How should I deal with unmatched ve开发者_StackOverflow社区ctor lengths: use Assertions, IllegalArgumentException
, create my own Checked Exception class or what?
Note the function is in a library which is going to be used by other programmers, but it's very important that if vectors doesn't match developer be notified.
Here's the rule of thumb I use.
If it's something you EXPECT and RECOVER FROM, use a CHECKED exception.
If it's something that is probably a PROGRAMMER ERROR and is not expected to ever happen, use a RUNTIME exception.
You can't really recover from this without more user input, so it sure sounds like an IllegalArgumentException
to me.
I would throw an IllegalArgumentException. Make sure you document this in the Javadocs.
/**
* returns the sum of this vector and another vector.
* @param other the second summand. It must have the same
* length as this vector.
* @return the sum of both vectors as a new vector.
* @throws IllegalArgumentException if the two vectors do not have
* the same length (i.e. come from different vector spaces).
*/
public Vector plus(Vector other) {
if (this.length != other.length) {
throw new IllegalArgumentException("different lengths: " + this.length + "!=" + other.length);
}
...
}
An ArithmeticException
would be another possibility, but I think an `IllegalArgumentException fits it better.
Checking with assert
is normally switched off and has to be enabled explicitly, often only while testing the application, not in productive use. Thus this is only suitable for checking in private methods, which always should get correct parameters (ensured by checks in the calling methods).
If it's a case that the caller will be able to recover from, then throw a Checked Exception. If it's a case that the caller won't be able to recover from, throw an Unchecked Exception (e.g. IllegalArgumentException
). asserts will really only be useful for tracking down errors in yours/their code, so that's probably not the right way to solve what you're talking about.
Both IllegalArgumentException
and IndexOutOfBoundsException
are fine choices. You should document this, and include the lengths in the exception message.
精彩评论