Error: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown[7]

StackOverflow https://stackoverflow.com/questions/22878833

  •  28-06-2023
  •  | 
  •  

Question

I keep getting the FileNotFoundException, even though I´m throwing it.

Here´s the code:

import java.util.*;
import java.io.*;
    
public class kt_6_2 {
    public static void main(String[] args) {
        File file = new File("magicSquare.txt");
        fileRead(file);
    }
    static void fileRead (File dummyFile) throws FileNotFoundException {
        Scanner scanner = new Scanner(dummyFile);
        String[] squareLines = new String[3];
        for (int a = 0; a < 3; a++) {
            squareLines[a] = scanner.nextLine();
            scanner.nextLine();
        }
        System.out.println(squareLines[2]);
    }
}

edit: the error message is:

kt_6_2.java:7: error: unreported exception FileNotFoundException; must be caught
 or declared to be thrown
                fileRead(file);
                        ^
1 error
Was it helpful?

Solution

Since your main method is calling your fileRead() method. And instead of handling exception your fileRead() method has decided to throw the Exception.

So in exception scenario, once its thrown from fileRead() method it should be caught in your main() method. However, your main() can further throw this exception.

you need to write as

public static void main(String[] args) throws FileNotFoundException {
 ....

or if you want to handle the exception, you should write as:

public static void main(String[] args) {
    File file = new File("magicSquare.txt");
     try{
        fileRead(file);
      } catch (FileNotFoundException ex) {
           //exception handling code
      }
  } 

OTHER TIPS

must be caught or declared to be thrown

What exactly do you not understand here? You use a method fileRead that can throw FileNotFoundException, hence you must either catch it, or hand it upwards, so your main method would need a throws clause.

But the latter choice is, of course, a bad one. So simply wrap that readFile invokation in a try/catch block.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top