Java:startingPath为"public static final"异常

hhh*_*hhh 0 java static scope final

[更新,对不起有关更改,但现在对真正的问题] 我不能在那里包含try-catch-loop来获取方法getCanonicalPath()的异常.我试图先用方法解决问题,然后在那里声明值.问题是它是最终的,我无法改变它.那么如何将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
Run Code Online (Sandbox Code Playgroud)

Kev*_*ock 5

您可以提供静态方法来初始化静态变量:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

或者您可以在静态块中初始化变量:

public static final String startingPath;

static {
    try {
        startingPath = new File(".").getCanonicalPath();
    } catch (IOException e) {
        throw new RuntimeException("Got I/O exception during initialization", e);
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:在这种情况下你的变量是static这样的,没有办法声明抛出的异常.仅供参考,如果变量是非变量,则static可以通过在构造函数中声明抛出的异常来执行此操作,如下所示:

public class PathHandler {

    private final String thePath = new File(".").getCanonicalPath();

    public PathHandler() throws IOException {
        // other initialization
    }
Run Code Online (Sandbox Code Playgroud)

  • 我经常抛出ExceptionInInitializerError. (3认同)