So far, you've just acquired exceptions thrown by the Java runtime System. However, a program can throw a definite exception with a throw statement. The usual form of a throw statement is as follows:
Throw throwableinstance;
Here, throwableinstance must be an object of the Throwable class type or Throwable subclass type. Simple types, such as int or char, and non-throwable classes, such as String or object, cannot be used as exceptions. There are two ways to get a Throwable object: Use a parameter in a catch clause or create it with the new operator.
The program execution stops immediately after the throw statement, and any subsequent statements are not executed. The most tightly enclosed try block is used to check if it contains a catch statement that matches the type of the exception. If a matching block is found, the control turns to the statement, and if it is not found, the second enclosing try block is checked, and so on. If no matching catch block is found, the default exception handler interrupts the execution of the program and prints the stack trace.
Here is an example program that creates and throws an exception, and the handler that matches the exception throws it to the outer handler.
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);
}
}
}
The program has two opportunities to handle the same error. First, main () sets up an exception relationship and then calls Demoproc (). The Demoproc () method then establishes another exception-handling relationship and immediately throws a new NullPointerException instance, NullPointerException is captured on the next line. The exception is then thrown again. The following is the output result:
Caught inside Demoproc.
Recaught:java.lang.NullPointerException:demo
The program also explains how to create a standard exception object for Java.pay special attention to the following line:
throw New NullPointerException ("demo");
Here, new is used to construct a nullpointerexception instance. All Java built-in runtime exceptions have two constructors: one with no parameters and one with a string argument. When the second form is used, the parameter specifies the string that describes the exception. If the object is used as a parameter to print () or println (), the string is displayed. This can also be done by calling GetMessage (), which getMessage () is defined by Throwable.
Java Throw: Exception throws what's going on