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,