What..When...?
I always wonder, why Java is not intelligent enough to fix problems in the code when it knows something goes wrong; rather than throwing just exceptions? May be Gosling wants it that way, saving donuts for him!
Now read on...
public class A{ public static void main(String []s) throws ClassNotFoundException, InstantiationException, IllegalAccessException{ B obj = new B(); // Class.forName("B").newInstance(); } }
1 public class B{ 2 }
javac A.java
java A
This would throw a NoClassDefFoundError. Comment out line 4 and uncomment line 5. Now it would throw ClassNotFoundException.
ClassNotFoundexception is thrown when an application tries to load in a class through its string name using:
The forName method in class Class.
The findSystemClass method in class ClassLoader .
The loadClass method in class ClassLoader.
Otherwise NoClassDefFoundError is thrown.
The interesting fact is that, this behaves differently when your application runs in OC4j Oracle application server. i.e. your application would throw a NoClassDefFoundError to ClassNotFoundException.
If you dont want to miss your donut, add two catch blocks in your code...I already missed one..:(
try{ //... }catch(ClassNotFoundexception e1){ }catch(NoClassDefFoundError e2){ }
No comments:
Post a Comment