Java: startingPath as “public static final” exception

后端 未结 5 1101
天涯浪人
天涯浪人 2021-01-26 13:00

[Updated, sorry about the change but now to the real problem] I cannot include try-catch-loop there for the exception from the method getCanonicalPath(). I trie

5条回答
  •  攒了一身酷
    2021-01-26 13:36

    The name is fine; you forgot to declare the type.

    public static final String startingPath;
    //                  ^^^^^^
    

    Fixing that, you of course realize the harder problem of how to deal with the possible IOException and startingPath being final. One way is to use a static initializer:

    JLS 8.7 Static Initializers

    Any static initializers declared in a class are executed when the class is initialized and, together with any field initializers for class variables, may be used to initialize the class variables of the class.

     public static final String startingPath;
     static {
        String path = null;
        try {
          path = new File(".").getCanonicalPath();
        } catch (IOException e) {
          // do whatever you have to do
        }
        startingPath = path;
     }
    

    Another way is to use a static method (see Kevin Brock's answer). That approach actually results in better readability, and is the recommended approach by Josh Bloch in Effective Java.


    See also

    • How to handle a static final field initializer that throws checked exception?
    • In what order do static initializer blocks in Java run?

提交回复
热议问题