首页 > 解决方案 > 简单java归档代码中的FileNotFound Exception错误

问题描述

我刚开始这个项目,并试图检查我是否走对了路。我运行这段代码,但得到一个“必须捕获或抛出 FileNotFound 异常”错误。现在我该怎么做?我走对了吗?

package com.company;
import java.util.Scanner;
import java.io.File;

public class Main
{

public static void main(String[] args)
{
Game game = new Game();
String s = game.OpenFile();
System.out.println(s);
}
}




class Game
{
    public Game(){
        moviename = " ";
    }
    private String moviename;
    public String OpenFile()
    {
        File file = new File("movienames.txt");
        Scanner ip = new Scanner(file);
        int rnum = (int)(Math.random()*10)+1;
        int count = 0;
        while(ip.hasNextLine())
        {
            moviename = ip.nextLine();
            count++;
            if(count==rnum)
            {
                break;
            }
        }
    return moviename;
    }

标签: javaexceptioncompiler-errorsfile-handlingjava-io

解决方案


是的,你走对了。这个警告的意思是你必须处理FileNotFound异常。您有两种选择:将其扔掉或将代码包围在一个try-catch块中:

抛出异常:

public String OpenFile() throws FileNotFoundException
{
    File file = new File("movienames.txt");
    Scanner ip = new Scanner(file);
    int rnum = (int)(Math.random()*10)+1;
    int count = 0;
    while(ip.hasNextLine())
    {
        moviename = ip.nextLine();
        count++;
        if(count==rnum)
        {
            break;
        }
    }
return moviename;
}

尝试捕捉

public String OpenFile() 
{
    try {
        File file = new File("movienames.txt");
        Scanner ip = new Scanner(file);
        int rnum = (int)(Math.random()*10)+1;
        int count = 0;
        while(ip.hasNextLine())
        {
          moviename = ip.nextLine();
          count++;
          if(count==rnum)
          {
              break;
           }
        } 
    }catch(Exception e) {
        e.printStackTrace();
    }
    return moviename;

一些不错的读物:

java中try-catch和throw的区别

https://beginnersbook.com/2013/04/try-catch-in-java/


推荐阅读