我写了下面的代码:如何捕捉异常在静态初始化块抛出
static {
/* Attempts to load JDBC driver */
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new DBConfigurationException("JDBC Driver not found.", e);
}
/* Attempts to load configuration */
conf = loadConfiguration(); //this may throw some subclasses of RuntimeException
}
,因为我想JDBC驱动程序和配置中只有一次加载。
我想要做这样的事情在启动(我将简化尽可能地):
public static void main(String[] args) {
try {
// load the class that contains the code above
} catch (DBConfigurationException e) {
// display proper error message using JOptionPane, then quit
} catch (MissingConfigurationException e) {
// display proper error message using JOptionPane
// show a JDialog and allow user to input and store a configuration
} catch (InvalidConfigurationException e) {
// display proper error message using JOptionPane
// show a JDialog and allow user to input and store a configuration
}
/* if everything it's ok */
// do some other checks in order to decide which JFrame display first.
}
现在的问题是,如果有异常发生时,JVM将抛出广告ExceptionInInitializerError
和将只不构建对象。 也许我仍然可以明白出了什么问题,抓住ExceptionInInitializerError
(即使这听起来不对),并检查其原因(我仍然没有这样做,但我认为这是可能的)。
我需要该对象,因为万一异常是可恢复的(例如MissingConfigurationException),程序将不会退出并需要该对象。
我应该避免静态初始值设定项吗? 我可以这样做:
private static final Configuration conf = null;
Constructor() {
if (conf == null) {
/* Attempts to load JDBC driver */
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new DBConfigurationException("JDBC Driver not found.", e);
}
/* Attempts to load configuration */
conf = loadConfiguration();
}
}
但即使这样一个听起来不正确对我说:异常可能只在使用的第一次尝试(我知道会在启动时,因为我不得不这样做抛出检查),即当该类被加载。所以从理论上讲,第一种方法更为正确。 :\
我该怎么办?哪种方法更正确?
的问题是,与静态初始化类NEEDS司机和配置,所以它不应来之前他们两人都可以使用。 :\
根据定义,从'static {}'块抛出的异常生成ExceptionInInitializer并将类标记为不可用。这是它应该的方式(加上或减去一个小的三角洲)。 –