理解 Java try/catch
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1250860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
understanding the Java try/catch
提问by Aaron Moodie
I'm currently writing an app for school that is a mini search engine. On execution, it indexes the contents of the text files included as args. I haven't used the tryand catchmethods before, and we were just given this code as an include in our program:
我目前正在为学校编写一个应用程序,它是一个迷你搜索引擎。在执行时,它索引包含为 args 的文本文件的内容。我之前没有使用过try和catch方法,我们只是在我们的程序中包含了这段代码:
Scanner inputFile = null;
try {
inputFile = new Scanner(new File("dog.txt"));
} catch (FileNotFoundException fe) {
System.out.println("File not found!");
}
I've created a method that loops through the args and adds a new object to an array for every unique word found. The problem is that the catchmethod seems to still execute whenever I run the app, and I can't work out why. This is the output:
我创建了一个循环遍历 args 的方法,并为找到的每个唯一单词向数组添加一个新对象。问题是,catch每当我运行应用程序时,该方法似乎仍在执行,我不知道为什么。这是输出:
dog.txt being indexed ... File not found!
cat.txt being indexed ... File not found!
dog.txt 正在编入索引...文件未找到!
cat.txt 正在编入索引...文件未找到!
I've included the method below. If anyone cold maybe point out where I'm going wrong, that would be great.
我已经包含了下面的方法。如果任何感冒的人都可以指出我哪里出错了,那就太好了。
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!");
}
}
}
回答by paxdiablo
If you replace the line:
如果您更换该行:
System.out.println("File not found!");
with these lines:
用这些行:
System.out.println("File not found! " + fe);
fe.printStackTrace();
it should tell you exactly what the exception is (and the line number it occurred on).
它应该准确地告诉您异常是什么(以及它发生的行号)。
The next step is to use the fullpath name in the Scannerconstructor (e.g., "/tmp/dog.txt"). It may be that your IDE is running your code from a directory that's different from what you think it is.
下一步是在构造函数中使用完整路径名Scanner(例如,"/tmp/dog.txt")。可能是您的 IDE 正在从与您认为的目录不同的目录中运行您的代码。
You can figure out what actualdirectory you're in with:
您可以找出您所在的实际目录:
File here = new File (".");
try {
System.out.println ("Current directory: " + here.getCanonicalPath());
} catch(Exception e) {
e.printStackTrace();
}
回答by Timo Geusch
First thing I'd do is switch around these two lines so you only get the message if the file has actually been found:
我要做的第一件事是切换这两行,这样只有在实际找到文件时才会收到消息:
System.out.print((args[i]) + " being indexed ... ");
inputFile = new Scanner(new File(args[i]));
Basically, put them in like this:
基本上,把它们放在这样的地方:
inputFile = new Scanner(new File(args[i]));
System.out.print((args[i]) + " being indexed ... ");
It's less misleading this way IMHO.
恕我直言,这种方式误导性较小。
Other than that the code looks OK to me, but we're missing out the code for Scanner - I just checked and according to the Java docs (at least for 1.4.2), the File constructor doesn't throw a FileNotFoundException so something else must. Time to get the debugger out and find out exactly where the exception is thrown, or at least get a stack trace that shows you where it's thrown.
除此之外,代码对我来说看起来还不错,但是我们错过了 Scanner 的代码 - 我刚刚检查过并根据 Java 文档(至少对于 1.4.2),File 构造函数不会抛出 FileNotFoundException 所以一些东西否则必须。是时候让调试器出来并找出抛出异常的确切位置,或者至少获得一个堆栈跟踪,显示它在哪里抛出。
Also, you might have to qualify the path of the files you're trying to load if the working directory of your program is not where the files are; From your output it looks like you're not passing any path and you might have to.
此外,如果程序的工作目录不在文件所在的位置,您可能必须限定要加载的文件的路径;从您的输出来看,您似乎没有通过任何路径,您可能必须这样做。
回答by Charles Ma
Check to make sure that the file is in the right path (if you're using eclipse, set the run path to the directory of the file before executing.
检查以确保文件在正确的路径中(如果您使用的是 eclipse,请在执行前将运行路径设置为文件所在的目录。
Otherwise, use the full path name of the file and see if you're still getting this error.
否则,请使用文件的完整路径名,看看您是否仍然收到此错误。
If you moved the line
如果你移动了这条线
System.out.print((args[i]) + " being indexed ... ");
to the line after
到线后
inputFile = new Scanner(new File(args[i]));
I'm almost certain that "file being indexed ..." will not print
我几乎可以肯定“文件正在编制索引......”不会打印

