类变量中未处理的异常类型IOException

时间:2017-10-06 11:03:25

标签: java

我有一个类,我在其中填充变量值,如下所示

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。

1 个答案:

答案 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
}
相关问题