Reputation: 19
I have two constructors below and both executed just fine. Normally, Intellij will fuss at me if I didn't include throws in the method signature of the constructor, but in this particular instance, Intellij didn't bring up any errors. What would be the cause of this? I was taught to always put throws in the method signature if that method were to throw an exception. Is this a bug with Intellij?
protected PayCalculator(double payRate) throws IllegalArgumentException {
if (payRate >= 0)
this.payRate = payRate;
else
throw new IllegalArgumentException("Pay rate cannot be less than zero");
}
// versus
protected PayCalculator(double payRate) {
if (payRate >= 0)
this.payRate = payRate;
else
throw new IllegalArgumentException("Pay rate cannot be less than zero");
}
Upvotes: -1
Views: 188
Reputation: 158
An IllegalArgumentException
is a subtype of a RuntimeException
. So just like an ArrayIndexOutOfBoundsException
it doesn't need to be caught or thrown. Think of it like this snippet of Code
int foo() {
int[] bar = new int[2];
return bar[10];
}
This inevitably will throw an ArrayIndexOutOfBoundsException
but it'll compile just fine.
Upvotes: 1