[已更新,对更改感到抱歉,但现在是真正的问题了]对于 getCanonicalPath() 方法的异常,我无法在其中包含 try-catch-loop。我尝试先用方法解决问题,然后在那里声明值。问题是它是最终的,我无法更改它。那么如何将startingPath 设置为“public static final”。
$ cat StartingPath.java
import java.util.*;
import java.io.*;
public class StartingPath {
public static final String startingPath = (new File(".")).getCanonicalPath();
public static void main(String[] args){
System.out.println(startingPath);
}
}
$ javac StartingPath.java
StartingPath.java:5: unreported exception java.io.IOException; must be caught or declared to be thrown
public static final String startingPath = (new File(".")).getCanonicalPath();
^
1 error
您可以提供静态方法来初始化静态变量:
public static final String startingPath = initPath();
private static String initPath() {
try {
return new File(".").getCanonicalPath();
} catch (IOException e) {
throw new RuntimeException("Got I/O exception during initialization", e);
}
}
或者您可以在静态块中初始化变量:
public static final String startingPath;
static {
try {
startingPath = new File(".").getCanonicalPath();
} catch (IOException e) {
throw new RuntimeException("Got I/O exception during initialization", e);
}
}
EDIT:在这种情况下你的变量是static
所以没有办法声明抛出的异常。仅供参考,如果变量是非static
您可以通过在构造函数中声明抛出的异常来做到这一点,如下所示:
public class PathHandler {
private final String thePath = new File(".").getCanonicalPath();
public PathHandler() throws IOException {
// other initialization
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)