使用BufferedReader时如何抛出FileNotFoundException? [英] How to throw FileNotFoundException when using BufferedReader?

查看:286
本文介绍了使用BufferedReader时如何抛出FileNotFoundException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

有一个java.io.FileNotFoundException(关于我当我运行此代码时(我故意放一个不存在的文件)。但是,我已经在我的方法头中抛出了IOException。我该怎么办才能不再遇到此错误?

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?

推荐答案

所有添加抛出表示该方法可以引发 Exception ,如果您要处理 Exception 被抛出。为此,您可以将代码块包装为try-catch块。如果应该抛出 Exception ,则无法阻止它被抛出,但是try-catch块会使其抛出异常,以使您的程序不会崩溃。 Oracle教程很有帮助。

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

这篇关于使用BufferedReader时如何抛出FileNotFoundException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆