Java lazy loading exceptions -


i know in java, classes loaded using lazy manner, such aren't loaded before they're used. exceptions treated differently reason? came across situation classnotfound exception exception class, though no exceptions have been thrown.

example:

public class {        public static void main(string[] args) {        if( args.length == 1 ){           new c();       }        if( args.length > 2 ){  //          try { //              b.throwanexception(); //          } catch (com.google.protobuf.invalidprotocolbufferexception e) { //              e.printstacktrace(); //          }      }   }  } 

class b:

import com.google.protobuf.invalidprotocolbufferexception;  public class b {    static{     system.out.println( "load class b" );   }    static void throwanexception() throws invalidprotocolbufferexception{     throw new com.google.protobuf.invalidprotocolbufferexception("jkl");   }  } 

class c:

public class c {    static{     system.out.println( "load class c" );   }  } 

when run program 1 argument, get:

$java arg1 load class c 

however, if uncomment try/catch in class a, get:

$ java arg1 exception in thread "main" java.lang.noclassdeffounderror: com/google/protobuf/invalidprotocolbufferexception 

why java attempting load exception class when no exception has been thrown/the class has not been loaded?

vm needs prepare exception jump table, requires exception types mentioned in catch clauses. has setup before method invoked 1st time.

if program is

    if( args.length > 2 )         throw new invalidprotocolbufferexception(); 

or

    if( args.length > 2 )         try {             b.throwanexception();         } catch (exception e) {             e.printstacktrace();         } 

it'll fine since exception type not appear in catch clause.


jls not enforce how lazy class loading should - can lazy possible, on other hand, if vm chooses load classes front, , bail if cannot so, allowed jls. see http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.1.2

the resolution step optional @ time of initial linkage. implementation may resolve symbolic references class or interface being linked early, point of resolving symbolic references classes , interfaces further referenced, recursively. ............... implementation may instead choose resolve symbolic reference when actively used ............. loading , linkage errors occur before program executed if involved class or interface mentioned in class test or of further, recursively referenced, classes , interfaces

however, jls strict on when class initialization can happen. in example, exception class loaded early, it's initialization must not occur until new invalidprotocolbufferexception() reached.


Comments

Popular posts from this blog

node.js - Bad Request - node js ajax post -

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -