\如何在 Java 中从静态块抛出异常?\
javaobject oriented programmingprogramming更新于 2025/9/15 10:52:17
静态块是一组语句,JVM 将在执行 main() 方法之前执行这些语句。在类加载时,如果我们想要执行任何活动,我们必须在静态块内定义该活动,因为此块在类加载时执行。
从静态块抛出异常
- 静态块只能抛出RunTimeException,或者应该有一个 try 和 catch 块来捕获已检查的异常
- 当类由类加载器加载时,会出现静态块。代码可以采用静态块的形式,也可以作为对用于初始化静态数据成员的静态方法的调用。
- 在这两种情况下,编译器都不允许已检查异常。当发生未检查异常时,它将被ExceptionInInitializerError包装,然后在触发类加载的线程上下文中抛出。
- 尝试从静态块抛出已检查异常也是不可能的。我们可以在静态块中有一个try和catch块,其中可以从try块中抛出已检查异常,但我们必须在catch块中解决它。我们不能使用throw关键字进一步传播它。
示例
public class StaticBlockException {
static int i, j;
static {
System.out.println("In the static block");
try {
i = 0;
j = 10/i;
} catch(Exception e){
System.out.println("Exception while initializing" + e.getMessage());
throw new RuntimeException(e.getMessage());
}
}
public static void main(String args[]) {
StaticBlockException sbe = new StaticBlockException();
System.out.println("In the main() method");
System.out.println("Value of i is : "+i);
System.out.println("Value of j is : "+ j);
}
}
输出
In the static block Exception while initializing/ by zero Exception in thread "main" java.lang.ExceptionInInitializerError Caused by: java.lang.RuntimeException: / by zero at StaticBlockException.(StaticBlockException.java:10)
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

