方法是否可以在不声明 java.lang.Exception 的情况下抛出该异常?

java 8object oriented programmingprogramming更新于 2025/9/21 9:48:17

不可以,因此,要明确抛出任何异常,您需要创建该异常的对象并使用 throw 关键字抛出它。

如果不创建对象,您就无法明确抛出异常,但您可能会创建导致相应异常的场景。

示例

以下 Java 程序抛出 NullPointerException

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

输出

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

相关文章