Illustrating throws keyword - Java Program

Q. Write a program to illustrate the throws keywords in Java.

Answer:

Throws is used for method declaration and denotes which exception can be thrown by this method.
This example shows how checked exception propagate by throws keyword.

ThrowsDemo.java

public class ThrowsDemo
{
     static void throwMethod1() throws NullPointerException
     {
          System.out.println ("Inside throwMethod1");
          throw new NullPointerException ("Throws_Demo1");
     }
     static void throwMethod2() throws ArithmeticException
     {
          System.out.println("Inside throwsMethod2");
          throw new ArithmeticException("Throws_Demo2");
     }
     public static void main(String args[])
     {
          try
          {
               throwMethod1();
          }
          catch (NullPointerException exp)
          {
               System.out.println ("Exception is: " +exp);
          }
          try
          {
               throwMethod2();
          }
          catch(ArithmeticException ae)
          {
               System.out.println("Exception is: "+ae);
          }
     }
}


Output:

throw keyword