为什么不需要捕获/处理此引发的异常?

时间:2018-09-12 08:38:22

标签: java

我有这小段代码使我烦(基于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项目)。

这是特例吗?

任何解释表示赞赏,

0 个答案:

没有答案
相关问题