Can a method throw java.lang.Exception without declaring it in java?

Java 8Object Oriented ProgrammingProgramming

No, for that matter to throw any exception explicitly you need to create an object of that exception and throw it using the throw keyword.

Without creating an object you cannot throw an exception explicitly, you might create a scenario that causes the respective exception.

Example

Following Java program throws a NullPointerException

public class ExceptionExample {
   public static void main(String[] args) {
      System.out.println("Hello");
      NullPointerException nullPointer = new NullPointerException();
      throw nullPointer;
   }
}

Output

Hello
Exception in thread "main" java.lang.NullPointerException
   at MyPackage.ExceptionExample.main(ExceptionExample.java:6)
raja
Published on 06-Aug-2019 11:39:12
Advertisements