Throw keyword is used to fire the exception manually. If an unexpected or unwanted situation occurs within a program block, it is better to notify the application. This can be done by throwing an exception from the code. You can throw one of many java exceptions or can create a custom exception which should be subclass of one of the java exceptions. One can throw multiple exceptions from try-catch block
.
public class NegativeIntegerException extends RuntimeException {
public NegativeIntegerException(final String message) {
super(message);
}
}
public class TestC {
public boolean negativeTest(final int i) throws MyCustomException {
if(i < 0) {
throw new NegativeIntegerException("Number is negative");
}
return true;
}
}
Throws clause is used to declare the exception from a method. It gives an indication that the program method can throw an exception. Method can declare multiple exception usingthrows
keyword.
public void parent(){
try {
child();
} catch(MyCustomException e) { }
}
public void child throws MyCustomException {
//put some logic so that the exception occurs.
}
Recommend Reading