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

Java 8Object Oriented ProgrammingProgramming

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();
   }
}
raja
Updated on 20-Feb-2020 06:39:20

Advertisements