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();
   }
}
Updated on: 2020-02-20T06:39:20+05:30

381 Views

Kickstart Your Career

Get certified by completing the course

Get Started