title: Singleton and Exception
body: <p>Whats the best way to design a singleton class that could throw an exception?</p>
  
  <p>Here I have a Singleton (using Bill Pugh's method, documented in Wiki for Singleton).</p>
  
  <pre><code>    private static class SingletonObjectFactoryHolder{
      //1  
          private static final ObjectFactory INSTANCE = new ObjectFactory();
      }
  
      private ObjectFactory() throws Exception{
      //2
              //create the factory
      }
  
  
      public static ObjectFactory getInstance(){
      //3
          return SingletonObjectFactoryHolder.INSTANCE;
      }
  </code></pre>
  
  <p>If an exception is thrown at 2, I would like to propagate it to the caller. 
  However, I can't throw an exception from line 1.</p>
  
  <p>So, is my only option to return a null object if the singleton object wasn't created correctly?</p>
  
  <p>Thanks</p>
  
  <p>P.S I do realize that this Singleton can break if its loaded via different classloaders or if loaded reflexively, but it's good enough for my purpose.</p>
  
  <p><strong>//UPDATE</strong></p>
  
  <p>I am curious, can I not rearrange my design as below to throw exceptions?</p>
  
  <p>Also, I don't need any synchronization (the classloader guarantees that the static inner class will only loaded once and only when getInstance() is called). Thus, thread-safe and lazily-instantiated?</p>
  
  <pre><code> private static class SingletonObjectFactoryHolder{
          //1  
             public static ObjectFactory getInstance() throws Exception{
           return new ObjectFactory();
             }
   }
  
   private ObjectFactory() throws Exception{
          //2
          //create the factory
   }
  
  
   public static ObjectFactory getInstance(){
          //3
      return SingletonObjectFactoryHolder.getInstance();
   }
  </code></pre>
  
  <p>Thanks again.</p>