Compiler Error J0143

Cannot throw exception 'identifier' from static initializer

The compiler detected an attempt to throw an exception from within a static initializer. This error usually occurs when a throw statement is called or when an initialization of a static class instance occurs within a static initializer. To capture exceptions from static class instance intializations in a static initializer, use a try/catch block combination.

The following example illustrates this error:

public class Simple {
   
   static {
      ThrowClass TClass = new ThrowClass();
      // error: cannot throw exceptions 
      // within static initializers
   }
}

class ThrowClass {
   
   ThrowClass() throws Exception{}
   
}

The following example illustrates how to use the try/catch block combination to capture potential errors when initializing static class instances in a static initializer:

public class Simple{
   static ThrowClass thr;
   static{
     try{
        ThrowClass thr = new ThrowClass();
     }
     catch (Exception e){
         //Handle errors here from initialization of 'ThrowClass'
     }
   }
}

class ThrowClass {
   ThrowClass() throws Exception(){
      // Do something here
   }
}