日期:2014-05-20  浏览次数:20903 次

为嘛static块中try catch必须抛呢
public class TestHibernate {

private static final SessionFactory sessionFactory;

static{
try {
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new HibernateException(e.getMessage());
}

}
}

如果我不写throw new HibernateException(e.getMessage());eclipse编译private static final SessionFactory sessionFactory;这行就会报错,报错如下:
Multiple markers at this line
- The value of the field TestHibernate.sessionFactory is 
not used
- The blank final field sessionFactory may not have been 
initialized

请高人指点下下


------解决方案--------------------
Multiple markers at this line
- The value of the field TestHibernate.sessionFactory is 
not used
- The blank final field sessionFactory may not have been 
initialized

提示说的很明白,sessionFactory 没有被初始化,因为如果发生异常,而你在异常里未做任何处理,sessionFactory 就不会赋值
------解决方案--------------------
探讨

兄弟 你不知道final没有初始化 有一次赋值机会吗?

------解决方案--------------------
小绵羊解释的很清楚,static块内必须完成此成员的初始化,发生异常时sessionFactory 可能没有值
------解决方案--------------------
探讨
Multiple markers at this line
- The value of the field TestHibernate.sessionFactory is
not used
- The blank final field sessionFactory may not have been
initialized

提示说的很明白,sessionFactory 没有被……

------解决方案--------------------
try里面不一定可以赋值成功的。final变量初始化的时候必须赋初值,可以在构造函数(所有的都要),静态代码块,代码块中赋初值(非static,只是final),你选择的是在静态代码块,但是呢,try不一定可以赋值成功,也就是说,要在运行的时候才能确定是否可以给sessionFactory赋初值。这是不行的,在编译的时候编译器就要确定是否赋初值了。