Search code examples
javaexceptiontry-catchthrow

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;
}

Solution

  • 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.