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

方法可以在Java中抛出java.lang.Exception而不声明吗?

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 scheme that causes the corresponding exception.

Example

The following Java program triggers 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)