抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

Java常见异常

1
2
3
4
5
6
7
8
9
10
11
classDiagram
Object <|-- Throwable
Throwable <|-- Error
Throwable <|-- Exception
Error <|-- OutOfMemoryError
Error <|-- NoClassDefFoundError
Error <|-- StackOverflowError
Exception <|-- IOException
Exception <|-- RuntimeException
RuntimeException <|-- NullPointerException
RuntimeException <|-- IndexOutOfBoundsException

NoClassDefFoundError 异常原因处理

类初始化失败

如果一个类初始化失败,在第一次失败的时候会报错java.lang.ExceptionInInitializerError,第二次就会java.lang.NoClassDefFoundError

今天碰到这个问题了,查了一下午(2023-05-05),fuck

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.example.demo;

public class Main {
public static void main(String[] args) {
try {
new ClassNotDefErrorFromClassLoad();
} catch (Throwable e) {
e.printStackTrace();
}
new ClassNotDefErrorFromClassLoad();
}
}

class ClassNotDefErrorFromClassLoad {
private static final String ERROR = String.valueOf(1 / 0);
}
1
2
3
4
5
6
7
java.lang.ExceptionInInitializerError
at com.example.demo.Main.main(Main.java:6)
Caused by: java.lang.ArithmeticException: / by zero
at com.example.demo.ClassNotDefErrorFromClassLoad.<clinit>(Main.java:15)
... 1 more
Exception in thread "main" java.lang.NoClassDefFoundError: Could not initialize class com.example.demo.ClassNotDefErrorFromClassLoad
at com.example.demo.Main.main(Main.java:10)

class文件丢失

对下面这个类,启动后程序运行正常

1
2
3
4
5
6
7
8
9
10
11
package com.example.demo;

public class Main {
public static void main(String[] args) {
new ClassNotDefErrorFromClassNotFound();
}
}

class ClassNotDefErrorFromClassNotFound {
}

1
Process finished with exit code 0

我们观察编译的结果,发现两个class文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$ tree target/
target/
|-- classes
| |-- application.properties
| `-- com
| `-- example
| `-- demo
| |-- ClassNotDefErrorFromClassNotFound.class
| `-- Main.class
|-- generated-sources
| `-- annotations
|-- generated-test-sources
| `-- test-annotations
`-- test-classes

这时候我们删除ClassNotDefErrorFromClassNotFound.class,然后运行代码,发现报错NoClassDefFoundError

1
2
3
4
5
6
7
8
9
10
Exception in thread "main" java.lang.NoClassDefFoundError: com/example/demo/ClassNotDefErrorFromClassNotFound
at com.example.demo.Main.main(Main.java:5)
Caused by: java.lang.ClassNotFoundException: com.example.demo.ClassNotDefErrorFromClassNotFound
at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 1 more

Process finished with exit code 1

评论