Java, using throw without try block

18,403

Solution 1

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.

Solution 2

Yes it is ok. You simply need to add throws clause for method in case it throws a checked exception. There is no restriction of a try clause for throwing an exception. For example if you have a stack and called pop() method and size is zero you can check it and throw an exception. You may need to catch the exception wherever you plan to invoke this method. Otherwise this uncaught exception will move up the invocation stack and will be finally handled by JVM and it will print stack trace on System.err stream. We can also specify our own handler if we want:

public class CustomUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
  public void uncaughtException(Thread t, Throwable e) {
     // Write the custom logic here
   }
}

You do not even need to mention exception in throws if it is a RunTimException.

Share:
18,403
danger mouse
Author by

danger mouse

Updated on June 12, 2022

Comments

  • danger mouse
    danger mouse almost 2 years

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