我有一个类,我在其中填充变量值,如下所示
public class JSONDBWriter{
// JDBC driver name, database URL, Database credentials
private static final String JDBC_DRIVER = ReadPropertiesFile("JDBC_DRIVER");
private static final String DB_URL = ReadPropertiesFile("DB_URL");
private static final String USER = ReadPropertiesFile("USER");
private static final String PASS = ReadPropertiesFile("PASS");
public static void main(String[] args) {
但是,Java编译器给出错误“Unhandled Exception type IOException” 我的ReadPropertiesFile抛出IOException。
答案 0 :(得分:2)
使用静态初始化程序。
public class JSONDBWriter {
public static String driver;
static {
try{
driver = //...
} catch (IOException e){
//
}
}
//other methods
}
如果您希望变量最终,请尝试以下内容:
public class Test {
public static final String test = getDataNoException();
private static String getData() throws IOException {
return "hello";
}
private static String getDataNoException() {
try {
return getData();
} catch (IOException e) {
e.printStackTrace();
return "no data";
}
}
//other methods
}