Java给了我一个错误"java.io.ioexception is never thrown in body of corresponding try statement"



所以我正在制作一个从.ppm文件渲染图片的程序。我有另一个版本在工作,但现在已转到另一部分,即从同一文档中读取多个图像,并且基本上使用它来动画,在切换图片之间有一小段延迟,然后出现以下错误并完全被它难倒了:

java.io.ioexception is never thrown in body of corresponding try statement

任何帮助将不胜感激。

public void renderAnimatedImage(){       
String image = UI.askString("Filename: ");
int keepingCount =0;      //Variables
int numCount = 1;    
try{
Scanner fileScan = new Scanner(image);    // making scanners
Scanner scan = new Scanner(image);
File myFile = new File(image);      //making files
File myFile2 = new File(image);
int num = 0;
while(scan.hasNextLine()){
String Line = scan.nextLine();
Scanner keywordSc = new Scanner (Line);
while(keywordSc.hasNext()) {
String Keyword = keywordSc.next();
if (Keyword.equals("P3")) {
num++;
}
else { break; }
}
}

while (keepingCount< numCount) {
this.renderImageHelper(scan);   // calling upon an earlier method which works.
keepingCount++;
}
}
catch(IOException e) {UI.printf("File failure %s n", e); }

}

这意味着您在try/catch中编写的代码永远不会抛出IOException,这使得该子句变得不必要。您可以删除它并保留没有它的代码。

我敢打赌,由于这一行,您认为可能存在IOException:

Scanner fileScan = new Scanner(image);    // making scanners

但这条线并没有像你认为的那样。 由于image是一个String因此将使用Scanner(String)构造函数。 但该构造函数将其参数视为要扫描的字符串,而不是要扫描的文件的名称。

因此,new Scanner(image)没有执行任何I/O,并且未声明为抛出IOException

块中的其余代码也不会抛出IOException。 如果在读取时出现 I/O 错误,则您使用的Scannernext/hasNext 方法将引发不同的异常。 (查看javadocs。


另外,您似乎误解了File是什么/做什么。

File myFile = new File(image);      //making files

注释不正确。 这不会生成文件。

实际上,它制作了一个File对象,该对象是文件名/路径名的内存表示形式。 创建File对象不会导致在文件系统中创建文件。 (再次检查javadocs。

最新更新