为什么我会捕捉异常
我正在运行以下代码以尝试从文本文件读取数据。我对Java相当陌生,一直在尝试为自己创建项目来练习。下面的代码稍微修改了我最初尝试读取文本文件的内容,但由于某种原因,它每次都会捕获异常。它试图从中读取的文本文件只有“hello world”。我认为它不能找到文本文件。我把它放在与源代码相同的文件夹中,它出现在源码包中(我使用netbeans btw)。它可能只是需要导入不同,但我无法找到任何进一步的信息。如果我的代码在这里是相关的,那么它在下面。为什么我会捕捉异常
package stats.practice;
import java.io.*;
import java.util.Scanner;
public final class TextCompare {
String NewString;
public static void main() {
try {
BufferedReader in = new BufferedReader(new FileReader("hello.txt"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
} catch (IOException e) {
}
System.out.println("Error");
}
}
第一步,替换下面的代码
catch (IOException e){}
与
catch (IOException e) { e.printStackTrace(); }
并且还替换
main()
与
main(String[] args)
这会告诉你确切的原因。然后你必须解决实际的原因。
现在对于Netbeans,文件hello.txt
必须在您的Netbeans项目中。像
<project_dir>
|
-->hello.txt
-->build
-->src
它不一定每次都会捕捉异常。您的System.out.println("Error");
声明不在catch块中。因此,每次程序执行时都会执行它。
为了解决这个问题,在大括号(catch (IOException e) {System.out.println("Error");}
)
在catch
块中的右括号是错误的内移动它。将其移动到System.out.println("Error");
以下。
public static void main(String[] args) {
try {
BufferedReader in = new BufferedReader(new FileReader("hello.txt"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
} catch (IOException e) { // <-- from here
System.out.println("Error");
// or even better
e.printStackTrace();
} // <-- to here
}
作为防御性编程的问题(预Java 7中至少),你应该在finally
块始终贴近资源:
public static void main(String[] args) {
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("hello.txt"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {}
}
// or if you're using Google Guava, it's much cleaner:
Closeables.closeQuietly(in);
}
}
如果您使用的是Java 7,你可以利用自动资源管理通过try
-with-resources:
public static void main(String[] args) {
try (BufferedReader in = new BufferedReader(new FileReader("hello.txt"))) {
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
是的,但它应该打印比错误更好的东西,所以你可以看到问题是什么。 – 2011-12-26 23:35:59
当然,编辑... – 2011-12-26 23:36:35
+1,因为你快! – 2011-12-26 23:37:17
你有一个空的catch块,这几乎总是一个坏主意。尝试把这里:
... catch (IOException ex) {
ex.printStackTrace();
}
而你应该很快看到发生了什么。
谢谢。替换文本文件的位置是它所需要的。 – Zombian 2011-12-26 23:57:25