MOR
MOR

Reputation: 11

FileNotFound Exception error in simple java filing code

I just started with this project and tried to check whether I was going the right way. I run this code but got one "FileNotFound exception must be caught or thrown" error. What do I do now? Am I going the right way?

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

Upvotes: 0

Views: 54

Answers (1)

GBlodgett
GBlodgett

Reputation: 12819

Yes you are going in the right way. What this warning is saying is that you must handle the FileNotFound exception. You have two options: Throw it or surround the code in a try-catch block:

Throwing the exception:

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

Try-Catch:

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;

Some good readings:

Difference between try-catch and throw in java

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

Upvotes: 1

Related Questions