0

While learning exceptions i tried the following steps and found a very strange behavior. Please find the steps below.

  • Created a Public Class A
  • Create a class B
  • Compiled A and B
  • Deleted the class B before running A

After doing above steps program runs absolutely fine and throws NoClassDefFoundError ,Now strange thing is when i declare the reference variable inside the try block and run the program again it throws an uncaught NoClassDefFoundError

public class A{
    public static void main(String[] args) {
           B m ;//Caught is getting printed if declare above try-catch()
        try {
            B m = new B();//Here Uncaught exception is throws
        } catch (java.lang.NoClassDefFoundError ex) {
            System.out.println("Caught!");
        }
    }
}

class B{

}

I really don't have any idea why this is happening please help me understand this

T-Bag
  • 10,916
  • 3
  • 54
  • 118

1 Answers1

2

You are deleting the class file of A after B has compiled and generated bytecode. So, code of B still references A and when your A starts running, the JVM will try to load and initialize B when the object is being created and since it cannot find the class in the class path of A, it throws NoClassDefinitionFoundException.

In your fist case you just declare a reference to B, the JVM will NOT try to load your class unless it really needs it, so you wont get any exception.

TheLostMind
  • 35,966
  • 12
  • 68
  • 104