Java 给我一个错误“java.io.ioexception 永远不会在相应的 try 语句主体中抛出”

问题描述 投票:0回答:3

所以我正在制作一个从 .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); }



}
java ioexception
3个回答
4
投票

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


2
投票

我敢打赌,您认为可能会因为这一行而出现 IOException:

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

但是这条线并没有像你想象的那样做。 由于

image
String
,因此将使用
Scanner(String)
构造函数。 但该构造函数将其参数视为要扫描的字符串,而不是要扫描的文件的名称。

因此

new Scanner(image)
不执行任何 I/O,也没有声明为抛出
IOException

块中的其余代码也不会抛出

IOException
。 如果读取时出现 I/O 错误,您使用的
Scanner
next / hasNext 方法将引发不同的异常。 (检查 javadocs。)


另外,你似乎误解了

File
是什么/做什么。

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

评论不正确。 那不会生成文件。

实际上,它创建了一个

File
对象,它是文件名/路径名的内存表示。 创建
File
对象不会导致在文件系统中创建文件。 (再次检查 javadocs。)


0
投票

您需要这样修改方法的标头:

public void renderAnimatedImage() throws IOException { 
.
.
.

© www.soinside.com 2019 - 2024. All rights reserved.