Throwing any exception makes the current method exit immediately, but not the whole program. Furthermore, the exception will continue being thrown at the calling method, from where the first method threw it; this is called propagation. Whether it keeps going at that point depends on whether that calling method catches the exception. If nothing catches the exception, it'll propagate all the way back to the main
method (this is assuming a simple, single-threaded application), and if that method also throws it, then the program will exit.
void callee() {
if (someTrueCondition()) {
throw new IllegalArgumentException("whatever");
}
System.out.println("this will never get called");
}
void caller() {
calle(); // the IllegalArgumentException propagates from here
System.out.println("this will also never get called");
}
The above is true for any exception. What makes IllegalArgumentException
different from others is only the fact that it's unchecked, and thus doesn't need to be declared in a throws
clause on the method that may throw it. (Note that in your question, you said you probably would need to declare throws IllegalArgumentException
, but you actually don't, because it's an unchecked exception.)
If you were instead throwing a checked exception (e.g., throw new SQLException()
), then both callee
and caller
would need to declare that exception. callee
would need to declare it because it throws that exception directly, and caller
would need to declare it because it may throw that exception indirectly, via propagation from callee
.
The only way to stop this propagation (both of the exception at runtime, and of the throws
clauses at compile-time) is to catch the given exception with a try-catch
.