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


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)

Updated on: 06-Aug-2019

125 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements