Share this page 

Static field, constructor and exceptionTag(s): Language


Consider the following class
public class Foo {
   private static Bar b = new Bar();
   ...
 }

class Bar {
  public Bar ( ) throws Exception {
  }
} 
it will not compile because Bar() is declared to throw an exception.

To solve this situation, use a static block.

public class Foo {
  static Bar bar ;

  static {
    try {
       bar  = new Bar() ;
    } 
    catch ( Exception e ) {
      e.printStackTrace() ;
    }
  }
}

class Bar {
  public Bar ( ) throws Exception {
  }
}