Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why throwing an exception tries to loads the class which extends Exception (though it is not executed) but not a regular class

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");
        }
    }
}

enter image description here

Thanks for help

like image 658
Shiva Avatar asked Feb 21 '19 14:02

Shiva


1 Answers

(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

like image 82
OhleC Avatar answered Nov 11 '22 10:11

OhleC