-6

Can anyone tell me why I have this error: exception java.io.FileNotFoundException is never thrown in body of corresponding try statement. I try to save text from a file in an ArrayList.

import java.io.*;
    import java.util.*;

    public class EditMembership
    {
        public static void main(String[] args) throws java.io.FileNotFoundException
        {

            ArrayList<String> member = readFromFile("database.txt");
            System.out.println(Arrays.toString(member.toArray()));
        }

        public static ArrayList readFromFile(String fileName) throws java.io.FileNotFoundException
        {

            Scanner x = new Scanner(new File(fileName));
            ArrayList<String> memberList = new ArrayList<String>();
            try {
                while (x.hasNextLine()) 
                {

                    memberList.add(x.nextLine());
                }
                x.close();
            }
            catch(FileNotFoundException e)//here is the error
            {
                e.printStackTrace();
            }
            return memberList;
        }
    }
ade
  • 9
  • 1
  • 4

1 Answers1

3

Because you aren't doing anything to open a file within the try block it's impossible to throw a File Not Found. Move the Scanner declaration down within the try block and I would expect that'll fix it. At that point you can remove the "throws" declaration from your method signature.

osoblanco
  • 468
  • 2
  • 10