理解Java try/catch

Aar*_*die 1 java

我正在为学校编写一个迷你搜索引擎的应用程序.在执行时,它将包含为args的文本文件的内容编入索引.我之前没有使用过trycatch方法,我们刚刚将这段代码作为包含在我们的程序中:

Scanner inputFile = null;
try {
    inputFile = new Scanner(new File("dog.txt"));
} catch (FileNotFoundException fe) {
    System.out.println("File not found!");
}
Run Code Online (Sandbox Code Playgroud)

我创建了一个循环遍历args的方法,并为找到的每个唯一单词向数组添加一个新对象.问题是,catch每当我运行应用程序时,该方法似乎仍然执行,我无法解决原因.这是输出:

dog.txt被索引...找不到文件!
cat.txt被索引...找不到文件!

我已经包含了以下方法.如果有人感冒可能会指出我哪里出错了,那就太好了.

static void createIndex(String[] args) {
    for(int i = 0; i < args.length; i++) {
        Scanner inputFile = null;
        try {
            System.out.print((args[i]) + " being indexed ... ");
            inputFile = new Scanner(new File(args[i])); 
            while(inputFile.hasNext()) {
                boolean isUnique = true;
                String newWord = inputFile.next().trim().toLowerCase();
                for(int j = 0; j < uniqueWords; j++)
                    if(newWord.equals(wordObjects[j].getWord())) {
                        wordObjects[j].setFile(args[i]);
                        isUnique = false;
                    }

                if(isUnique) {
                    wordObjects[uniqueWords] = new WordIndex(newWord, args[i]);
                    uniqueWords++;
                }
            }

            System.out.print("done");

        } catch(FileNotFoundException fe) {
            System.out.println("File not found!");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

pax*_*blo 5

如果你更换线:

System.out.println("File not found!");
Run Code Online (Sandbox Code Playgroud)

用这些线:

System.out.println("File not found! " + fe);
fe.printStackTrace();
Run Code Online (Sandbox Code Playgroud)

它应该准确地告诉你异常是什么(以及它出现的行号).

下一步是在构造函数中使用完整路径名Scanner(例如,"/tmp/dog.txt").可能是您的IDE正在从与您的想法不同的目录运行代码.

你可以弄清楚你所在的实际目录:

File here = new File (".");
try {
   System.out.println ("Current directory: " + here.getCanonicalPath());
} catch(Exception e) {
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)