Java: throw vs throws vs Throwable
throw
is a statement that causes an exception to be thrown:
void method(int i) {
if (i < 0)
throwCauses the IllegalArgumentException
to be thrown. new IllegalArgumentException();
...
}
throws
is used in method declarations to say that a given exception may be thrown by the method.
void method() throwsSays that this method may throw IOExceptions
IOException {
if (ioError)
throw new IOException();
...
}
Throwable
is the root class of all objects that can be thrown. If you want to catch all kinds of throwables you could do
try {
processRequest();
} catch (ThrowableCatches everything t) {
log.error("Request error: " + t);
}
(This just for illustrative purposes. Catching Throwable
is considered bad practice, but that's a topic for another article).
Comments
Be the first to comment!