Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, using throw without try block

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;
}
like image 626
danger mouse Avatar asked Mar 17 '23 05:03

danger mouse


1 Answers

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.

like image 72
underdog Avatar answered Mar 24 '23 12:03

underdog