开发者

Why am I getting an error message "unreported exception Java.io in a java code when trying to read from a text file"?

开发者 https://www.devze.com 2023-04-13 06:21 出处:网络
I\'m new to java and I\'m still having issues. I have written code that reads all its data from a text file. It compiles okay but when I try and instantiate the the code from another class it gives m

I'm new to java and I'm still having issues.

I have written code that reads all its data from a text file. It compiles okay but when I try and instantiate the the code from another class it gives me the following error:

"unreported exception java.io.fileNotFoundException, must be caught or declared to be thrown".

I understand that their are probably issues with my throws try catch that I have and have not included but I dont really know how to use these and I would appreciate some assistance with it.

Thanks everyone who can help

This is the code

    import java.io.*;
    import java.io.FileNotFoundException;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.*;
    import java.util.Scanner;

    public class readTextFile1
    {
        private static int index = 0;
        private static int numberOfDepartmentsToRead;
        private static int i;

        private static  ArrayList<Employee> allEmployees = new ArrayList<Employee>();


        public readTextFile1()
            throws FileNotFoundException
            {

                Scanner inFile = new Scanner (new File("startup.txt") );

                storageSystem theStorageSystem = new storageSy开发者_开发知识库stem();       

                numberOfDepartmentsToRead = inFile.nextInt();

                String depName      = inFile.nextLine();
                System.out.println("this is the first one "+depName);

                while  (index < numberOfDepartmentsToRead ) 
                {

                    String depName1    = inFile.nextLine();
                    System.out.println("this should be the department name"+depName1);
                    String location1     = inFile.nextLine();
                    System.out.println("this should be the location"+location1);
                    String numberOfEmps = inFile.nextLine();
                    int    numberOfEmps1 = Integer.parseInt(numberOfEmps);
                    System.out.println("this is the number of employees: "+numberOfEmps1);
                    Department newDepartment = new Department(depName1 , location1);
                    theStorageSystem.setDepartment(newDepartment);

                    while (i < numberOfEmps1 )
                    {
                        String fName     = inFile.nextLine();
                        System.out.println("his first name is: "+fName);
                        String lName     = inFile.nextLine();
                        System.out.println("his last name is"+ lName);
                        String gender    = inFile.nextLine();
                        System.out.println("his gender is: "+gender);
                        String address   = inFile.nextLine();
                        System.out.println("his adrs is: "+address);
                        String   payLevel  = inFile.nextLine(); 
                        System.out.println("and this is the pay level"+payLevel);
                        int dPayLevel = Integer.parseInt(payLevel);
                        Employee employeesFromList = new Employee(fName, lName, gender, dPayLevel, "1er-543");
                        theStorageSystem.setEmployee(employeesFromList);
                        i++;
                    }   
                    i = 0;
                 index++;   
                }

                        while (inFile.hasNextLine())
                        {
                            String fName     = inFile.nextLine();
                                System.out.println("his first name is: "+fName);
                                String lName     = inFile.nextLine();
                                System.out.println("his last name is"+ lName);
                                String gender    = inFile.nextLine();
                                System.out.println("his gender is: "+gender);
                                String address   = inFile.nextLine();
                                System.out.println("his adrs is: "+address);
                                String   payLevel  = inFile.nextLine(); 
                                System.out.println("and this is the pay level"+payLevel);
                                int dPayLevel = Integer.parseInt(payLevel);
                                Employee employeesFromList = new Employee(fName, lName, gender, dPayLevel, "1er-543");
                                theStorageSystem.setEmployee(employeesFromList);
                            //  allEmployees = theStorageSystem.getEmployee();  
                        }

                        }

                    public ArrayList<Employee> giveEmployeeTf()
                    {
                        return allEmployees;
                    }
        }


Every moethod in java must declare the exceptions it might throw [except RuntimeExceptions]. Since your method throws FileNotFoundException, it must do one of 2 things:

  1. declare it as throws FileNotFoundException

  2. use a try,catch block, and handle this exception.

(*)The above is referring to the activation of your constructor, i.e. the method that is actually activating the c'tor.


You should probably surround your use of the readTextFile1() method within a try-catch block:

readTextFile1 cls = new readTextFile1();

try
{
    cls.readTextFile1();
}
catch (FileNotFoundException e)
{
    // report error or something
}

Additionally your class is misnamed as it doesn't describe its use; it appears to store a list of Employee objects and reads that data using this method. You would do better to call the class DepartmentReader or something (note the leading uppercase letter).


If exceptions are possible in your code, you have two options:

  • Catch them (and optionally handle them) or
  • rethrow them.

Catching them is done by blocks starting with try{} and ending in catch(Exceptiontype exceptionname) (with optional finally{} block).

Throwing them further up means that you let the calling stack further up handle the exception. For this purpose, you defined your class with the phrase "throws FileNotFoundException". This means that from now on, using this method in any code will need to acknowledge this optional exception, again either by catching it or throwing it further up still.

So whenever you use the method above, you need to do one of the two mentioned things, and I'm sure you missed both.


You might want to read up on exceptions and exception handling.


        public readTextFile1()
            throws FileNotFoundException

This declares that readTextFile1 can throw FileNotFoundException, which is a so-called checked exception. That means that, at the point you call this method, you must either catch it, or explicitly declare that the calling method can also throw this.

Catching it would work thusly:

readTextFile1 file = new readTextFile1();
try {
    readTextFile1.readTextFile1();
} catch (FileNotFoundException ex) {
    // Here, handle the case that the file is not found. For example:
    System.err.println("File not found");
}

(By the way, class names in Java are usually written with a capital letter, and should be in the form of a noun, not a verb. For example, TextFileReader.)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号