Throw and throws
Throw: create an exceptional situation explicitly
An exception does not have to arise on its own because of division by zero or an invalid index.
Code can explicitly report that normal execution cannot continue.
The throw statement is used for this.
static void validateAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("age");
}
System.out.println("valid");
}
The expression new IllegalArgumentException("age") creates an exception object,
and throw starts it as an exceptional situation.
If age is negative, the line with valid will no longer run during that method call.
Normal execution stops after throw
As soon as throw executes, Java stops normal execution of the current code path
and looks for a suitable handler. The familiar catch can handle the thrown object
if its type matches the handler.
try {
validateAge(-5);
System.out.println("after call");
} catch (IllegalArgumentException e) {
System.out.println("caught");
}
System.out.println("done");
The call to validateAge(-5) reaches throw,
so after call is not printed. Control moves to the catch,
and after it finishes, the program continues and prints done.
Throws describes that an exception may leave a method
The throws keyword is written in a method declaration after the parameter list.
It shows that an exception of the specified type may leave the method and move to the calling code.
static void checkAccess(boolean allowed) throws Exception {
if (!allowed) {
throw new Exception("denied");
}
}
Here, throw executes inside the method body and actually throws an exception object,
while throws Exception is in the signature and describes the possibility that this exception leaves the method.
By itself, throws neither throws nor handles anything.
throw and throws solve different tasks.
throw is an action inside the code: throw a specific exception object.
throws is part of a method declaration: specify the type of exception that may leave it.
An exception can pass through several calls
A method does not have to handle an exception in the same place where it originated.
If there is no suitable catch inside the method, the exception may move to the calling code,
where it can be handled.
static void open() throws Exception {
checkAccess(false);
}
try {
open();
} catch (Exception e) {
System.out.println("caught");
}
In this example, the exception is created and thrown in checkAccess(),
passes through open(), and is handled by the outer catch.
This is how throw, throws, and the familiar catch
work together: an exception originates in one place, may be passed upward, and can be handled where the code provides for it.