If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception.
we do this by including a throws clause in the method’s declaration. A throws clause lists the types of exceptions that a method might throw.
This is necessary for all exceptions, except those of type Error or RuntimeException, or any of their subclasses. All other exceptions that a method can throw must be declared in the throws clause. If they are not, a compile-time error will result
General form of a method declaration that includes a throws clause
type method-name(parameter-list) throws exception-list
{
// body of method
}
class ThrowsDemo {
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
}
}
Output
inside throwOne
caught java.lang.IllegalAccessException: demo