首页  

NoClassDefFoundError和ClassNotFoundException异常的区别     所属分类 java 浏览量 1098
java.lang.ClassNotFoundException
java.lang.NoClassDefFoundError


ClassNotFoundException
Thrown when an application tries to load in a class through its string name using:
1. The forName method in class Class.
2. The findSystemClass method in class ClassLoader .
3. The loadClass method in class ClassLoader.
but no definition for the class with the specified name could be found.

ClassNotFoundException 原因是类找不到 classpath里 缺少class文件或jar文件

java.lang.NoClassDefFoundError 一般由类初始化失败引起的

譬如某个类MyUtil 静态初始化抛异常 java.lang.ExceptionInInitializerError

使用初始化失败的类会报 java.lang.NoClassDefFoundError
譬如 java.lang.NoClassDefFoundError: Could not initialize class NoClassDefTest$MyUtil

完整测试代码 NoClassDefTest.java



import java.util.Date;

public class NoClassDefTest {
	
	public static void main(String[] args) throws Exception {
		System.out.println("NoClassDefTest");

		try {
			MyUtil.hello();
		} catch (Throwable e) {
			System.out.println(e);
		}

		try {
			MyUtil.hello();
		} catch (Throwable e) {
			System.out.println(e);
		}

	}

	private static class MyUtil {

		static {
			init();
		}

		private static void init() {
			throw new RuntimeException("init error");
		}

		public static void hello() {
			System.out.println("hello," + new Date());
		}

	}

}


程序输出如下:

NoClassDefTest
java.lang.ExceptionInInitializerError
java.lang.NoClassDefFoundError: Could not initialize class NoClassDefTest$MyUtil

上一篇     下一篇
域名查询命令

java线程状态

互联网新老词汇对照表

进程线程与协程的区别

ExecutorService中submit和execute的区别

java thread join实现原理