0

nullpointerexception が発生しています。実際に何が原因なのかわかりません。fileinputstream は securityexception のみをスローするという Java ドキュメントを読んだので、この例外がポップアップする理由がわかりません。ここに私のコードスニペットがあります。

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

41 行目で実行中の変数 prop は null ですか? これを確認するには、プログラムをデバッグしてみてください。例: 追加

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

また、NullPointerException は未チェックの例外であるため、Javadoc には記載されていません。

于 2010-04-15T21:31:29.120 に答える
1

他のレビュアーがあなたの問題を説明するのに公正な仕事をしたと思います.

いくつかのポインタ:

  1. 特定の例外をキャッチしているが、それらをスローしていないことに気付きました。例外をスローしない場合、それらをキャッチしても意味がありません。

  2. 次に、NPE を回避するために、オブジェクトに対して何かを実行する前に、オブジェクトのいずれかが null かどうかを常に確認する必要があります。

于 2010-04-15T22:10:53.140 に答える