Java The Throw Statement with Examples

Java The Throw Statement with Examples


Throw Keyword In Java
So far, you have only been catching exceptions that are thrown by the Java run-time system. However, it is possible for your program to throw an exception explicitly, using the throw statement. The general form of throw is shown here -
 
throw ThrowableInstance;
 
Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable. Primitive types, such as int or char, as well as non-Throwable classes, such as String and Object, cannot be used as exceptions.
Now we will see an Example -
Example -
 
// Demonstrate throw.
class ThrowDemo {
static void demoproc() {
try {
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 {
demoproc();
} catch(NullPointerException e) {
System.out.println("Recaught: " + e);
}
}
}
 
Explanation -
This program gets two chances to deal with the same error. First, main( ) sets up an exception context and then calls demoproc( ). The demoproc( ) method then sets up another exceptionhandling context and immediately throws a new instance of NullPointerException, which is caught on the next line. The exception is then rethrown. 
Output - 
A sample output would be  -
 
Caught inside demoproc. Recaught: java.lang.NullPointerException: demo