gpt4 book ai didi

java - 我收到错误 : "exception FileNotFoundException is never thrown in body of corresponding try statement" and cannot figure out why

转载 作者:行者123 更新时间:2023-12-01 13:03:40 25 4
gpt4 key购买 nike

这是我的代码:

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

错误是:错误:相应 try 语句的主体中永远不会抛出异常 FileNotFoundException为什么我会得到这个?我认为它不抛出异常是一件好事,为什么它必须告诉我这一点,你知道吗?我真的不明白这个。

最佳答案

您收到此错误是因为在 try 语句中,据编译器所知,您没有调用任何可能引发此错误的方法。

由于方法必须声明它们抛出的异常,因此此错误告诉您正在 try catch 永远不会发生的异常,这是一个编码错误。

也许您有此方法的早期版本,可能会引发此错误?如果是这样,也许发生这种情况是因为你改变了方法,所以它不再可能了?这只是我的猜测,但是您发布的代码示例不会尝试打开任何新文件(这是在 try 语句开始之前完成的),因此它可以' t 发生在 try 的主体内。

关于java - 我收到错误 : "exception FileNotFoundException is never thrown in body of corresponding try statement" and cannot figure out why,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23375515/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com