For the following method, is it okay to throw the exception when it isn't inside a 'try' block?
public void setCapacity(x) throws CapacityExceededException {
if (x > 10) throw new CapacityExceededException(x);
else this.x = x;
}
Yes it is Ok to throw an exception when it isn't inside a try block. All you have do is declare that your method throws an exception. Otherwise compiler will give an error.
public void setCapacity(x) throws CapacityExceededException {
if (x > 10) throw new CapacityExceededException(x);
else this.x = x;
}
You don't even have to do that if your CapacityExceededException
extends Runtime Exception.
public void setA(int a) {
this.a = a;
if(a<0) throw new NullPointerException();
}
This code won't give any compiler error. As NPE is a RuntimeException.
When you throw an exception the exception will be propagated to the method which called setCapacity()
method. That method has to deal with the exception via try catch or propagate it further up the call stack by rethrowing it.
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