如果不加if,编译器会提示“initializer does not complete normally”
不加if的情况:会报错,显示错误信息:“initializer does not complete normally”
class DeadLoopClass{
static {
System.out.println(Thread.currentThread()+"DeadLoopClass init!!!");
while(true){
}
}
}
加if的情况:能编译通过
class DeadLoopClass{
static {
if(true) {
System.out.println(Thread.currentThread()+"DeadLoopClass init!!!");
while(true){
}
}
}
}
解析:
解析1:因为static方法,是类初始化的时候进行的。如果没加if,那么就会进入while的死循环,虚拟机检查不通过。
解析2:没加if的时候,虚拟机只检查最外层代码,因为有while的死循环;如果加了if以后,就只单纯检查If语句,虚拟机不会检查到while的死循环语句块。
拓展:在静态语句块中,也不能抛出异常,否则编译不通过。
没加if的情况:会报错,显示错误信息:“initializer does not complete normally”
class DeadLoopClass{
static {
throw new RuntimeException();
}
}
加if的情况:能正常编译通过
class DeadLoopClass{
static {
if(true) {
throw new RuntimeException();
}
}
}
网友评论