I have a class named as MyClass
, so when i called
classloader.loadClass("myclass")
throws a NoClassDefFoundError
instead of a ClassNotFoundException
.
Note - I have changed the upper case letter to small case letter
When i used completely different string "ABC" i get ClassNotFoundException
as expected .
Please find the code snippet below.
public class Test {
public static void main(String[] args) {
// normal conditions
try {
Test.class.getClassLoader().loadClass("MyClass");
System.out.println(" Successfully loaded an existing class ");
} catch (ClassNotFoundException notExpected) {
}
// expected
try {
Test.class.getClassLoader().loadClass("ABC");
} catch (ClassNotFoundException expected) {
System.out.println("Expected");
}
try {
Test.class.getClassLoader().loadClass("myclass");
} catch (ClassNotFoundException expected) {
System.out.println("Expected but not coming");
}
}
}
//
// sample class used for the above in separate file
//
public class MyClass
{
}
OutPut:
Successfully loaded an existing class
Expected
Exception in thread "main" java.lang.NoClassDefFoundError: myclass (wrong name: MyClass)
[![Output on Java 8 Machine][1]][1]
It is not duplicate as I am looking for different exceptions on name change scenario please check again