ClassNotFoundException v/s NoClassDefFoundError

ClassNotFoundException

ClassNotFoundException Thrown when an application tries to load in a class through its name as String. (When Dynamic loading).
Here is one simple example to throw class not found Exception

public class ClassNotFoundTest {
	public static void main(String[] args) {
		try {
				ClassLoader myClassLoader = ClassLoader.getSystemClassLoader();
				String className = "testclass";
				Class<?> myClass = myClassLoader.loadClass(className);
				System.out.println("Successfully loaded"+myClass.getSimpleName());	
			}
			catch (ClassNotFoundException  e) {
				System.out.println("Exception message   "+e);
			}
	}
}


Exception message   java.lang.ClassNotFoundException: testclass



NoClassDefFoundError


NoClassDefFoundError Thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class and no definition of the class could be found.

The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found.

No comments:

Post a Comment

12 classic String-based Java interview questions with simple explanations and code.

  1️⃣ Check if a String is a Palindrome Problem Given a string, check if it reads the same forward and backward. Example: "madam...

Featured Posts