Mark Said Camilleri
Mark Said Camilleri

Reputation: 388

Error: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown

I am trying to code a telephone directory for my java project (MATSEC 'O' Levels equivalent to the British GCSE) and while coding (using BlueJ) this error pops up. I am using my teacher's book as a reference and there is nothing related to the error and it doesn't say that I should add anything to it. Here is my java code (Not the main class):

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

Basically, this simply reads from a text file and displays the entries. I am not yet using GUI.

Upvotes: 0

Views: 1104

Answers (3)

Dedyshka
Dedyshka

Reputation: 471

Try to use modern IDE, for example, Eclipse. It will help to you to detect many compilation errors.

Upvotes: 0

DRastislav
DRastislav

Reputation: 1882

please put your Buffered Reader in try catch block :)

Upvotes: 1

kosa
kosa

Reputation: 66667

Your file reading code inside read() method should be wrapped inside try/catch block

(or)

define read() method as read() throws FileNotFoundException { .....}.

FileNotFoundException is checked exception, it should be either declared in throws clause (or) Code which may throw this exception should be wrapped in try/catch due to catch/specify requirement.

Upvotes: 2

Related Questions