English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

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

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

If you do not create an object, you cannot explicitly throw an exception, and you may create a scenario that causes the corresponding exception.

Example

The following Java program throws NullPointerException

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

Output Result

Hello
Exception in thread "main" java.lang.NullPointerException
   at MyPackage.ExceptionExample.main(ExceptionExample.java:6)