2010-04-15 5 views
0

nullpointerexception이 발생하고 실제로 어떤 원인인지 알 수 없습니다. java docs에서 fileinputstream은 securityexception 만 던져서이 예외가 왜 나타나는지 이해하지 못한다. 여기 내 코드 조각입니다. 라인 (41) this.prop.load(in); 경우FileInputStream이 NullPointerException을 throw합니다.

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

고맙습니다. – Mohamed

답변

1

다음은 this.prop == null

을 확인하기 위해 줄에 중단 점을 추가 것처럼 보인다

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

여기 내 스택 트레이스입니다.

null 인스턴스에서 메소드를 호출하면 NullPointerException이됩니다.

1

변수 41은 41 행에서 실행될 때 null입니까? 프로그램을 디버깅하여이를 확인하십시오. 예 : add

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

또한 NullPointerException은 확인되지 않은 예외이므로 Javadoc에 문서화되어 있지 않습니다.

1

다른 검토자가 문제를 설명하는 데 공정한 일을했다고 생각합니다. 포인터의

커플 :

  1. 난 당신이 특정 예외를 잡기하지만 그들을 던지고되지 않은 것으로 나타났습니다. 예외를 throw하지 않으면 예외를 포착 할 필요가 없습니다.

  2. 두 번째로 NPE를 피하려면 개체에서 아무것도 실행하기 전에 개체가 Null인지 항상 확인해야합니다.

관련 문제