开发者

FileInputStream throws NullPointerException

开发者 https://www.devze.com 2022-12-27 05:46 出处:网络
I am getting nullpointerexception, don\'t know what actually 开发者_JAVA百科is causing it. I read from java docs that fileinputstream only throws securityexception so don\'t understand why this except

I am getting nullpointerexception, don't know what actually 开发者_JAVA百科is causing it. I read from java docs that fileinputstream only throws securityexception so don't understand why this exception pops up. here is my code snippet.

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

and here is my stacktrace:

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


If line 41 is this.prop.load(in); then it seems as though this.prop == null

Add a breakpoint on the line to verify.

Attempting to call a method on a null instance results in a NullPointerException.


Is the variable prop null when it is executing on line 41? Try debugging your program to check this. e.g. add

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

Also, NullPointerException is an unchecked exception so isn't documented in Javadoc.


I think the other reviewers did a fair job in explaining your problem.

Couple of pointers:

  1. I noticed that you are catching certain exceptions but not throwing them. If you do not throw the exception then there is no point in catching them.

  2. Secondly, to avoid NPEs you should always check if any of your object is null before executing anything on the object.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号