Pages

ClassNotFoundException vs NoClassDefFoundError

 When a specific class is not found at runtime, errors such as ClassNotFoundException and NoClassDefFoundError are generated. However, they occur in various different circumstances.


When the Class.forName() or loadClass() methods are used to load a class at runtime and the requested classes are not present in the classpath, a ClassNotFoundException exception is thrown.

An error known as NoClassDefFoundError is produced when a specific class is present at compile time but not at run time.


ClassNotFoundException

ClassNotFoundException is a runtime exception that is thrown when an application tries to load a class at runtime using the Class.forName() or loadClass() or findSystemClass() methods ,and the class with specified name are not found in the classpath. For example, you may have encountered this exception when you try to connect to MySQL or Oracle databases and have not updated the classpath with the required JAR files. Most of the time, this exception occurs when you try to run an application without updating the classpath with the required JAR files.

For example, the below program will throw ClassNotFoundException if the mentioned class “oracle.jdbc.driver.OracleDriver” is not found in the classpath.


If you run the above program without updating the classpath with required JAR files, you will get an exception akin to:



NoClassDefFoundError

NoClassDefFoundError is an error thrown when the Java Runtime System tries to load the definition of a class, and that class definition is no longer available. The required class definition was present at compile time, but it was missing at runtime. For example, compile the program below.


When you compile the above program, two .class files will be generated. One is A.class and another one is B.class. If you remove the A.class file and run the B.class file, Java Runtime System will throw NoClassDefFoundError like below:


No comments:

Post a Comment