This section describes about throwing Exception explicitely in java.
How to throw Exception
Until now, we are 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. You can throw exception explicitly as follows :
throw ThrowableInstance ;
ThrowableInstance must be an object of type 'Throwable' or a subclass of 'Throwable'.
Example :
public class ThrowDemo {
static void DevProc() {
try {
throw new NullPointerException("demo");
} catch (NullPointerException e) {
System.out.println("Caught inside Devproc.");
throw e;
}
}
public static void main(String args[]) {
try {
DevProc();
} catch (NullPointerException e) {
System.out.println("Recaught :" + e);
}
}
}
Output :
|
C:\Program Files\Java\jdk1.6.0_18\bin>javac ThrowDemo
.java C:\Program Files\Java\jdk1.6.0_18\bin>java ThrowDemo Caught inside Devproc. Recaught :java.lang.NullPointerException: demo |

[ 0 ] Comments