未处理的异常类型为IOException

问题描述:

我有一个类我在哪里填充变量值如下未处理的异常类型为IOException

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编译器是给错误“未处理的异常类型为IOException” 我ReadPropertiesFile抛出IOException异常。

+0

ReadPropertiesFile()是方法和手段的不直接叫成类。他们需要其他方法,构造函数或块来调用。 –

+0

它在哪条线上抛出错误? –

使用静态初始化器。

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 
} 
+0

我的变量是最后的 –

+0

@AbhijitKumarSingh检查编辑答案。 –