java 异常之: Could not initialize class

时间:2025-04-01 15:42:39

异常描述:在实例化类对象的时候,抛出异常: Could not initialize class
原因:一般有该异常是因为实例化的目标类有static部分,且在加载static的时候失败
代码示例

public class NoClassDefFoundErrorTest {
    static {
        int i = Integer.parseInt("rtt");
    }

}

可以看上面是一个简单的测试类,NoClassDefFoundErrorTest。该类只有一个static代码块,在代码块中只有一行代码int i = (“rtt”);,因为“rtt”无法转换成int类型,所以必然会失败,且抛出异常。
接下来是执行类

public class NoClassDefFoundErrorTest2 {
    public static void main(String[] args) {
        new NoClassDefFoundErrorTest();
    }
}

NoClassDefFoundErrorTest2 类中只有一个main(),在main()中也只是初始化了一个NoClassDefFoundErrorTest对象,并没有其他的任何操作。在run NoClassDefFoundErrorTest2 会发现抛出了如下异常信息

Caused by: java.lang.NumberFormatException: For input string: "rtt"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Integer.parseInt(Integer.java:580)
	at java.lang.Integer.parseInt(Integer.java:615)
	at com.NoClassDefFoundErrorTest.<clinit>(NoClassDefFoundErrorTest.java:5)
	... 1 more