忽略空点异常并继续

时间:2016-10-17 12:54:31

标签: java

我写了一些代码,它从一个充满地址的文本文件中输入一个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);
            }
        }

1 个答案:

答案 0 :(得分: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());
                }