Java:startingPath为"public static final".例外 [英] Java: startingPath as "public static final" exception

查看:81
本文介绍了Java:startingPath为"public static final".例外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[已更新,对更改感到抱歉,但现在是真正的问题] 我不能在其中包括try-catch-loop来获取方法getCanonicalPath()的异常.我试图通过方法来更早地解决问题,然后在其中声明值.问题是它是最终版本,我无法更改.那么如何将startingPath作为"public static final".

[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 tried to solve the problem earlier with method and then declaring the value there. The problem is that it is Final, I am unable to change it. So how to have startingPath as "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

推荐答案

名字很好;您忘记声明类型了.

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

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


解决了这一问题,您当然意识到了如何处理可能的IOExceptionstartingPathfinal的难题.一种方法是使用static初始化程序:


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:

在初始化类时,将执行在类中声明的任何静态初始化器,并且可以将其与任何用于类变量的字段初始化器一起使用,以初始化该类的类变量.

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;
 }

另一种方法是使用static方法(请参见凯文·布洛克(Kevin Brock)的答案).这种方法实际上可以提高可读性,并且是Josh Bloch在有效Java 中推荐的方法.

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.

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

这篇关于Java:startingPath为"public static final".例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆