Search code examples
javaexceptionbufferedreader

How to throw FileNotFoundException when using BufferedReader?


import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Random;

public class WordList {
    private static Random r = new Random();

    private static ArrayList<String> words = new ArrayList<String>();
    String filename = "Cities.txt";

    public static void main(String[] args) throws IOException {
        WordList wl = new WordList();
        buffR(wl.filename);
        System.out.println(words);
        System.out.println(getRandomWord());
    }

    public static ArrayList buffR(String filename) throws IOException {
        words.clear();
        String line = null;
        BufferedReader br = null;

        br = new BufferedReader(new FileReader(filename));
        while ((line = br.readLine()) != null) {
            words.add(line);
        }
        br.close();
        return words;
    }

    public static String getRandomWord() {
        WordList wl = new WordList();
        String randomWord;
        if (words.size() > 0) {
            int index = r.nextInt(words.size());
            randomWord = words.get(index);
        } else {
            randomWord = wl.filename + " is missing";
        }
        return randomWord;
    }
}

There is a java.io.FileNotFoundException (regarding my BufferedReader method) when I run this code(I intentionally put a no existing file). However, I already threw IOException in my method header. What should I do to not encounter this error again?


Solution

  • All that adding a throws does it say that the method can throw an Exception, you want to be handling an Exception if it is thrown. To do this, you can wrap the code chunk is a try-catch block. There is no way to stop an Exception from being thrown if it should be thrown, but the try-catch block will make it so that your program doesn't crash. The Oracle Tutorial is quite helpful.

    For this example, you would do something like this:

    try 
    {
      //This already throws FileNotFoundException
      br = new BufferedReader(new FileReader(filename));
    } 
    catch(FileNotFoundException e)
    {
      e.printStackTrace();
    }