Exception throw


So far, you're only catching the exceptions thrown by the Java run-time system. However, your program can make an exception by using the throw statement. The simplest form of throwing is shown here :

throw ThrowableInstance;

Here, ThrowableInstance must be an object of Throwable type or a subclass of Throwable. Primitive types such as int or char, as well as non-throwable classes such as strings and objects, cannot be used as exceptions. You can achieve two Throwable objects: using a parameter in a catch clause or creating one with a new operator.

The flow of death stops as soon as the throw statement is made; No further statement is executed. The nearest enclosing try block is checked to see if there is a catch statement that catches this exception. If it finds any matches, the control is transferred to the statement. If not, the next detailed attempt statement will be inspected, etc. So if no match is found, the default exception handler stops the program and prints the stack trace.

Program
public class Main 
{
 static void Throwdemo()
  {
   try{
    throw new NullPointerException("demo");
   }
   catch(NullPointerException e){
    System.out.println("Caught inside Throwdemo.");
    throw e;
   }
  }
  public static void main(String[] args) 
  {
   try{
    Throwdemo();
   }
   catch(NullPointerException e){
    System.out.println("Recaught : " + e);
   }
  }
}