I have the below classes.
I have manually compiled the classes using javac and ran the Driver
class.
Later removed the entity.class
and MyCustomException.class
and ran the app like below.
java Driver test
The below error is complained about MyCustomException
is missing but not about the Entity
class. So, not clear why JRE complaining about MyCustomException
class but not the Entity
class.
Indeed I have removed code throw new MyCustomException();
but I did not encounter error about Entity
class.
Caused by: java.lang.NoClassDefFoundError: com/techdisqus/exception/MyCustomException
Please note that the IF condition will NOT be executed as I am passing command argument as test
Why is it throwing an exception is causing to load the MyCustomException
which would be never executed but the JVM does not load any other regular class unless condition is satisfied, as here Entity
class here. Please check Driver.java
below.
MyCustomException.java
public class MyCustomException extends RuntimeException {
}
Entity.java
public class Entity {
}
Driver.java
public class Driver {
public static void main(String[] args) {
String s = args[0];
if("true".equals(s)){
Entity entity = new Entity(); // This is not loaded, unless s is true
throw new MyCustomException(); // this is loaded even s is NOT true.
}else{
System.out.println("success");
}
}
}
Thanks for help
(this is an educated guess; I'm by no means an expert on JVM internals)
I assume the error happens during verification, when the loaded class undergoes some sanity checks so the runtime can make some assumptions later.
One of the checks is a typecheck of bytecode instructions. Specifically athrow
:
An athrow instruction is type safe iff the top of the operand stack matches Throwable.
So at this point, the classloader has to load MyCustomException
to check whether it extends Throwable
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With