Java throw statement
Description
We can throw an exception in case of an exception.
Syntax
The general form of throw is shown here:
throw ThrowableInstance;
Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable.
Note
There are two ways to obtain a Throwable object: using a parameter in a catch clause, or creating one with the new operator.
The flow of execution stops immediately after the throw statement; any subsequent statements are not executed.
Example
How to use Java throws statement?
public class Main {
static void aMethod() {
try {/*from w w w .ja v a2 s . c om*/
throw new NullPointerException("demo");
} catch (NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
}
public static void main(String args[]) {
try {
aMethod();
} catch (NullPointerException e) {
System.out.println("Recaught: " + e);
}
}
}
The code above generates the following result.