What is the difference between throw and throws keywords in Java?



The throw keyword is used to raise an exception explicitly.

Example

public class Test {
   public static void main(String[] args) {
      throw new NullPointerException();
   }
}

Exception in thread "main" java.lang.NullPointerException at a6.dateAndTime.Test.main(Test.java:5)

The throws keywords in Java used to postpone the handling of a checked exception.

public class Test {
   public static void main(String[] args)throws NullPointerException {
      throw new NullPointerException();
   }
}
Sharon Christine
Sharon Christine

An investment in knowledge pays the best interest


Advertisements