2016-10-17 65 views
-4

我已經寫了一些代碼,需要從一個文本文件的完整地址輸入的IP地址,將這些物理位置忽略零點異常,並進行

但是偶爾的結果會給出一個空指針異常 - 有點期待由於輸入的文本文件有時不是100%格式正確,但是當我有超過一百萬個地址的空指針異常可能有點討厭停止我的程序哈哈 - 我可以用這樣的方式編碼捕獲異常並繼續進行?

 public convert() { 

//   System.out.println("in test"); 
      Locate obj = new Locate(); 
      String file = "Bitcoin_IP.txt"; 

      try (BufferedReader br = new BufferedReader(new FileReader(file))) { 
       String line; 
       while ((line = br.readLine()) != null) { 
//    System.out.println(line); 

        ServerLocation location = obj.getLocation(line); 
        System.out.println(location); 

        try { 
         String filename = "Locations.txt"; 
         try (FileWriter fw = new FileWriter(filename, true)) { 
          fw.write(location + "\n"); 
         } 
        } catch (NullPointerException ioe) { 
         System.err.println("NullPointerException: " + ioe.getMessage()); 
        } 
       } 
      } catch (IOException ex) { 
       Logger.getLogger(Locate.class.getName()).log(Level.SEVERE, null, ex); 
      } 
     } 
+4

你爲什麼認爲這是預期的?我看不出爲什麼你會在你顯示的代碼中得到一個'NullPointerException' ... –

+2

(基本上,而不是捕捉'NullPointerException',你應該檢查相關變量的值是否爲null, ) –

+0

你有沒有考慮移動'ServerLocation location = obj.getLocation(line);在'try'塊內? – vikingsteve

回答

0

你已經趕上NPE的一些代碼,所以如果你仍然得到那些特殊的例外,他們必須發起位置:

   ServerLocation location = obj.getLocation(line); 

那麼試試這個:

   try { 
        ServerLocation location = obj.getLocation(line); 
        System.out.println(location); 

        String filename = "Locations.txt"; 
        try (FileWriter fw = new FileWriter(filename, true)) { 
         fw.write(location + "\n"); 
        } 
       } catch (NullPointerException ioe) { 
        System.err.println("NullPointerException: " + ioe.getMessage()); 
       } 
+1

你不應該捕獲空指針異常。相反,你應該檢查你的對象是否爲空。 if(obj!= null) –

+0

如果'getLocation(line)'拋出NullPointerException? – vikingsteve

+0

如果它來自你自己的圖書館,你應該檢查是什麼原因造成的。如果它是一個外部圖書館,並且你不能事先做檢查,那麼它就不在你的控制之下,並且你有一個合理的理由去捕捉一個NPE –