我有这小段代码使我烦(基于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;
}
尽管ExceptionInInitializerError
实际上报告它抛出了它,但我找不到在getSessionFactory()
中处理buildSessionFactory()
的原因不是强制性的。 Netbeans和编译器都没有给我错误(Java 8项目)。
这是特例吗?
任何解释表示赞赏,