How to solve ClassNotFoundException, NoClassDefFoundError and ExceptionInitializerError

1. ClassNotFoundException

1. Introduction

ClassNotFoundException is a checked exception.
Thrown when the application attempts to load a class by its string name, but a class with the specified name is not found in the classpath.
Generally occurs in Class.forName(String), ClassLoader.findSystemClass(String), ClassLoader.loadClass(String, boolean)

2. Common reasons

The essence of this exception is: there is no classes file specified to be loaded in your project!
  1. Missing jar package: The corresponding class is missing in the project.
  2. Incorrect jar package version: Maybe the same jar package does not have this class in version 1.0, but only exists in version 2.0.
  3. jar package conflict: There are multiple versions of the same jar package in the project, and the JVM loaded a version without the class.

2. NoClassDefFoundError

1. Introduction

NoClassDefFoundError exception, the naming suffix is an Error, and the user does not need to catch and handle it. It is obviously different from ClassNotFoundException.
This exception generally does not occur for classes written directly in this project. This exception usually occurs in a class in a jar that this project depends on.


















transfer







Call exception










This project









jar package A









Jar package B is missing

or

Another error occurred







For example, This project relies on jar package A and calls a method of a class in A. There is no problem with compilation at this time; but the execution of this method needs to depend on jar package B, but This project does not depend on jar package B, so this error will occur.

2. Common reasons

The essence of this exception is that the method of a certain class is available at compile time, but an error occurs at runtime.
  1. Missing jar package: When running method A, the jar package that method A depends on is missing.
  2. Incorrect jar package version: Maybe the same jar package does not have this class in version 1.0, but only exists in version 2.0.
  3. jar package conflict: There are multiple versions of the same jar package in the project, and the JVM loaded a version without the class.
  4. An error occurred while creating the object (constructor, static properties, static code blocks, etc. throw exceptions)

3. ExceptionInitializerError

1. Introduction

An exception occurred during initialization of a static code block or static variable.

2. Common reasons

  1. An error occurred in the constructor method.
  2. Static method and static property initialization errors.