我为什么要捕捉异常

时间:2011-12-26 23:30:30

标签: java exception-handling

我正在运行以下代码来尝试从文本文件中读取。我对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");
    }
}

4 个答案:

答案 0 :(得分:7)

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();
    }
}

答案 1 :(得分:3)

每次都不一定能抓住异常。您的System.out.println("Error");语句位于catch块之外。因此,每次程序执行时都会执行它。

要解决此问题,请在大括号(catch (IOException e) {System.out.println("Error");}

中移动它

答案 2 :(得分:2)

第一步,替换下面的代码

catch (IOException e){}

catch ( IOException e) { e.printStackTrace(); }

并替换

main()

main(String[] args)

这会告诉你确切的原因。然后你必须解决实际的原因。

现在对于Netbeans,文件hello.txt必须在您的Netbeans项目中。像

<project_dir>
    |
    -->hello.txt
    -->build
    -->src

答案 3 :(得分:1)

你有一个空的catch块,这几乎总是一个坏主意。试着把它放在那里:

... catch (IOException ex) {
  ex.printStackTrace();
}

你应该很快看到发生了什么。