I'm building a scientific software with lots of calculations and of course arguments can have wrong lengths etc... So I used IllegalArgumentException
class as it seemed right name for the issue, but should I put the throws IllegalArgumentException
at the function definition ?
I am asking this because after I wrote it, the Eclipse Editor didn't ask me to surround the function with try and catch. I thought this is how try and catch were enforced. I've read the Exception handling tutorial at Java.com yet I'm not sure I understood the part regarding my question right though.
The IllegalArgumentException is very useful and can be used to avoid situations where the application's code would have to deal with unchecked input data. The main use of this IllegalArgumentException is for validating the inputs coming from other users.
Because IllegalArgumentException is an unchecked exception, the Java compiler doesn't force you to catch it. Neither do you need to declare this exception in your method declaration's throws clause. It's perfectly fine to catch IllegalArgumentException , but if you don't, the compiler will not generate any errors.
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.
IllegalArgumentException CauseWhen a method is passed illegal or unsuitable arguments, an IllegalArgumentException is thrown.
public int calculateFactorial(int n) { if (n < 0) throw new IllegalArgumentException("n must be positive"); if (n >= 60) throw new IllegalArgumentException("n must be < 60"); ... } If you know that a parameter to your method cannot be null, then it is best to explicitly check for null and throw a NullPointerException.
RuntimeException
s like IllegalArgumentException
are used to indicate programming errors. The program itself should rarely be able to handle it. Someone needs to manually fix the code.
Potential RuntimeException
s should be documented somehow in the function contract (i.e. javadoc), either with the explicit @throws
, or while describing the inputs. If you don't have a javadoc for the function, you may want to add the throws clause just to document the potential pitfalls of using the function, but in general adding throws clauses for runtime exceptions is discouraged.
If giving a wrong length is not actually a programming error, but is an exception situation, I would create a new checked exception (such as BadLengthError). If it is not an exceptional situation, don't use exceptions for flow control.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With