0

I have this little piece of code which bugs me (based on this SO answer) :

private static SessionFactory sessionFactory = null;

/**
 *
 * @return the session factory
 * @throws ExceptionInInitializerError if the database cannot be
 *                                             opened / initialized for some
 *                                             reason
 */
private static SessionFactory buildSessionFactory() throws ExceptionInInitializerError{
    try {
    // Create the SessionFactory from hibernate.cfg.xml
    StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().configure().build();
    Metadata metadata = new MetadataSources(standardRegistry).getMetadataBuilder().build();
    return metadata.getSessionFactoryBuilder().build();
    } 
    catch (Throwable ex) {
        // Make sure you log the exception, as it might be swallowed
        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}

/**
 * 
 * @return the session factory to use to communicate with the database
 * @throws ExceptionInInitializerError if the db could not be initialized
 *  WHY ISN'T IT NECESSARY TO CATCH THE EXCEPTION THROWN BY buildSessionFactory() ? 
 */
public static SessionFactory getSessionFactory(){

    if (sessionFactory == null){
        // Here an exception can be thrown why isn't it compulsory to handle it ?
        sessionFactory = buildSessionFactory();
    }
    return sessionFactory;
}

I could not find why it is not compulsory to handle ExceptionInInitializerError in getSessionFactory() although buildSessionFactory() actually reports that it throws it. Neither Netbeans nor the compiler gives me errors (Java 8 project).

Is it a special case ?

Any explanation appreciated,

HelloWorld
  • 2,275
  • 18
  • 29
  • 1
    *Don't* throw `ExceptionInInitializerError` yourself. [Read the documentation](https://docs.oracle.com/javase/8/docs/api/java/lang/ExceptionInInitializerError.html): "Signals that an unexpected exception has occurred in a static initializer." This isn't a static initializer. Don't catch `Throwable` either. – Andy Turner Sep 12 '18 at 08:41
  • 1
    "Here an exception can be thrown" No, here an *`Error`* can be thrown. See [What is difference between Errors and Exceptions?](https://stackoverflow.com/questions/5813614/what-is-difference-between-errors-and-exceptions) – Andy Turner Sep 12 '18 at 08:42
  • Thank you @AndyTurner! Actually I missed the reading of [Is it possible to catch an ExceptionInInitializerError?](https://stackoverflow.com/questions/38931625/is-it-possible-to-catch-an-exceptionininitializererror) which is helpful as your link about the difference between Errors and Exceptions. I have never paid attention to this point so far! It's time to make progress!!! Thanks again. – HelloWorld Sep 12 '18 at 13:14

0 Answers0