0

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;
    }
3
  • It's a bit much dignifying this with the tag object-oriented-analysis when it's a mere file I/O program and the problem is a mere compiler error. Don't tag indiscriminately. Commented Jun 13, 2018 at 1:04
  • Okay. I understand. Commented Jun 20, 2018 at 1:49
  • It was a small excerpt from my project so yeah. Commented Jun 20, 2018 at 1:50

1 Answer 1

1

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/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.