甲静块是一组语句,这将是由JVM的执行之前被执行的main()方法。在类加载时,如果要执行任何活动,则必须在静态块中定义该活动,因为该块在 类加载时执行。
一个静态块只能抛出一个RuntimeException的,还是应该有一个try和catch块捕获一个检查异常。
甲静块 当一个类由类加载器加载发生。该代码可以是静态块的形式,也可以是用于初始化静态数据成员的静态方法的调用。
在这两种情况下,编译器都不允许检查异常。当一个未经检查的异常发生时,它被包裹的ExceptionInInitializerError,然后在触发类加载的线程的上下文抛出。
也无法尝试从静态块引发已检查的异常。我们可以在静态块中有一个try and 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)