Reputation: 13834
Imagine I have a class called A and a constructor that throws an exception of type B.
If I do A a = new A();
and my classpath doesn't contain B, will a java.lang.NoClassDefFoundError
error always be thrown? Or would it only be thrown if the constructor actually threw the Exception?
public class A{
public A() throws B{
if (...){
} else {
throw new B();
}
}
}
Upvotes: 1
Views: 1027
Reputation: 2848
WRONG ANSWER
Other answer is correct. The instantiation does not need to occur for the Error to be thrown.
NoClassDefFoundError
will be thrown on runtime when you try to instantiate a class that could not be found in the classpath.
In your example it will only be thrown when the else
block gets executed.
Doc is there: http://docs.oracle.com/javase/7/docs/api/java/lang/NoClassDefFoundError.html
Thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) 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.
Upvotes: 1
Reputation: 115338
Yes, NoClassDefFoundError
is always thrown when class loader tries to load class directly referenced in your code and cannot be found in class path.
If however you try to load this class dynamically, for example using Class.forName()
ClassNotFoundException
will be thrown.
Upvotes: 4