错误:未报告的异常java.io.FileNotFoundException;必须被抓住或宣布被抛出

时间:2012-12-17 19:09:27

标签: java

我正在尝试为我的java项目编写电话目录(相当于英国GCSE的MATSEC'O'级别),并且在编码时(使用BlueJ)会弹出此错误。我使用我的老师的书作为参考,并没有任何与错误相关的内容,也没有说我应该添加任何内容。这是我的java代码(不是主类):

import java.io.*;

class Data{
    String read(){  

        String[] name = null;
        String[] surname = null;
        String[] company = null;
        String[] house = null;
        String[] street = null;
        String[] locality = null;
        String[] telno = null;
        String[] mobno = null;
        int entnum;



        BufferedReader txt = new BufferedReader(new FileReader("Directory.txt"));

        System.out.println("Name\tSurname\tCompany\tHouse\tStreet\tLocality\tTelephone\tMobile");
            System.out.println("\n-----------------------------------------------------------------------------------------------");

        for(entnum = 0;name[entnum]!= null; entnum++){
            name[entnum] = txt.readLine();
            surname[entnum] = txt.readLine();
            company[entnum] = txt.readLine();
            house[entnum] = txt.readLine();
            street[entnum] = txt.readLine();
            locality[entnum] = txt.readLine();
            telno[entnum] = txt.readLine();
            mobno[entnum] = txt.readLine();

            System.out.print(name[entnum]+ "\t");
            System.out.print(surname[entnum]+ "\t");
            System.out.print(company[entnum]+ "\t");
            System.out.print(house[entnum]+ "\t");
            System.out.print(street[entnum]+ "\t");
            System.out.print(locality[entnum]+ "\t");
            System.out.print(telno[entnum]+ "\t");
            System.out.print(mobno[entnum]+ "\t\n");

            }
        return null;
    }
}

基本上,这只是从文本文件中读取并显示条目。我还没有使用GUI。

3 个答案:

答案 0 :(得分:2)

read()方法中的文件读取代码应该包含在try / catch块

(或)

将read()方法定义为read() throws FileNotFoundException { .....}

FileNotFoundException被检查异常,它应该在throws子句中声明(或)可能抛出此异常的代码应该包含在try / catch中,因为catch/specify的要求。

答案 1 :(得分:1)

请将您的Buffered Reader放入try catch块:)

答案 2 :(得分:0)

尝试使用现代IDE,例如Eclipse。它将帮助您检测许多编译错误。

相关问题