0

我收到 nullpointerexception,不知道实际上是什么原因造成的。我从 java 文档中读到 fileinputstream 只抛出 securityexception 所以不明白为什么会弹出这个异常。这是我的代码片段。

private Properties prop = new Properties();
private String settings_file_name = "settings.properties";
private String settings_dir = "\\.autograder\\";

public Properties get_settings() {
    String path = this.get_settings_directory();
    System.out.println(path + this.settings_dir + this.settings_file_name);
    if (this.settings_exist(path)) {
        try {
            FileInputStream in = new FileInputStream(path + this.settings_dir + this.settings_file_name);
            this.prop.load(in);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        this.create_settings_file(path);
        try{
            this.prop.load(new FileInputStream(path + this.settings_dir + this.settings_file_name));
        }catch (IOException ex){
            //ex.printStackTrace();
        }
    }
    return this.prop;
}

private String get_settings_directory() {
    String user_home = System.getProperty("user.home");
    if (user_home == null) {
        throw new IllegalStateException("user.home==null");
    }

    return user_home;
}

这是我的堆栈跟踪:

C:\Users\mohamed\.autograder\settings.properties
Exception in thread "main" java.lang.NullPointerException
        at autograder.Settings.get_settings(Settings.java:41)
        at autograder.Application.start(Application.java:20)
        at autograder.Main.main(Main.java:19)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

Line 41 is: this.prop.load(in);
4

3 回答 3

1

如果第 41 行是this.prop.load(in);那么它似乎this.prop == null

在行上添加断点进行验证。

尝试在 null 实例上调用方法会导致NullPointerException.

于 2010-04-15T21:28:04.457 回答
1

变量 prop 在第 41 行执行时是否为空?尝试调试您的程序以检查这一点。例如添加

if(prop == null)
    System.out.println("prop is null");

此外,NullPointerException 是未经检查的异常,因此未在 Javadoc 中记录。

于 2010-04-15T21:31:29.120 回答
1

我认为其他审稿人在解释你的问题方面做得很好。

几个指针:

  1. 我注意到您正在捕获某些异常但没有抛出它们。如果你不抛出异常,那么捕获它们是没有意义的。

  2. 其次,为了避免 NPE,在对对象执行任何操作之前,您应该始终检查您的任何对象是否为空。

于 2010-04-15T22:10:53.140 回答