Compiler Error J0238

Cannot throw exception 'identifier' from field initializer

The compiler detected that an exception was thrown within a field initializer. This error usually occurs when an exception is throwable from a constructor of a class, and an instance of that class is declared and instantiated as a member of another class. To resolve this problem, have the class object that throws the exception instantiated inside a constructor so it can use a try/catch combination to trap any exceptions from the other class's constructor call.

The following example illustrates this error:

public class Simple{
   public int i;
   public Simple(boolean var1) throws Exception{
      if (var1 = true)
         i = 0;
      else
         throw new Exception();
   }
}
//This is the incorrect way to instantiate this class
class Simple2{
   Simple smp = new Simple(true);
   /* error: cannot call constructor that throws exception in field
            initializer*/
}

The following code replaces the 'Simple2' class code in the example above to show the correct way to instantiate the 'Simple' class instance:

//This is the correct way to instantiate Simple
class Simple2{
   Simple smp;
   public Simple2(){
      try{
         smp = new Simple(true);}
      catch(Exception e){}
   }
}