简体   繁体   中英

I'm getting an error: “exception FileNotFoundException is never thrown in body of corresponding try statement” and cannot figure out why

Here is my code:

import java.util.Scanner;
import java.io.*;

public class Warning
{
    public static void main (String[] args)throws IOException
    {
        int creditHrs;         
        double qualityPts;     
        double gpa;            
        String name;

        // Set up scanner to input file
        Scanner inFile = new Scanner(new File("c:\\students.dat"));         
        System.out.println ("\n   Students on Academic Warning\n");

        // Process the input file, one token at a time
        try
        {   
            while (inFile.hasNext())
            {
                // Get the credit hours and quality points and
                // determine if the student is on warning. If so,
                // display the student's name.
                name = inFile.next();
                creditHrs = Integer.parseInt(inFile.next());
                qualityPts = Double.parseDouble(inFile.next());

                gpa = qualityPts / creditHrs;
                if(gpa < 2.0)
                {
                    System.out.println(name);
                }
            }
        }

        //insert catch statements
        catch(FileNotFoundException e)
        {
        }
        catch(NumberFormatException e)
        {
        }
        inFile.close();
    }
}

The error is: error: exception FileNotFoundException is never thrown in body of corresponding try statement Why am I getting this? I would think that it not throwing the exception is a good thing and why would it have to tell me that, you know? I really dont understand this.

You're getting this error because inside of the try statement you're not calling any methods that could even possibly throw this error, as far as the compiler can tell.

Since methods must declare the exceptions they throw, this error is telling you that you're trying to catch an exception that will never happen, which is a coding mistake.

Maybe you had a previous version of this method that might throw this error? If so, maybe this is happening because you've changed the method so it's no longer possible? This is just a guess on my part, but the code sample as you posted it doesn't try to open any new files (that is done before the beginning of the try statement), so it can't happen within the body of the try .

You are getting this error becuase FileNotFoundExeption will never be thrown by the piece of code inside try block. Try Changing FileNotFoundException to some other exception that will be thrown by the code section inside try block, or just catch Generic excepton (Exception).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM