当我尝试创建图像文件时,try-catch不会捕获IOException

时间:2017-11-25 17:20:45

标签: java eclipse exception try-catch

这是一个图像处理应用程序。我在下面显示的代码用于创建图像文件并将完全处理的BufferedImage保存到其中。

public static void saveAnh(BufferedImage anhHoanTat) {
    String dc;
    ui.save();
    input.nextLine();
    diachiluuanh = input.nextLine();
    dc = diachiluuanh 
        + diachi.substring(diachi.lastIndexOf("\\"), diachi.lastIndexOf(".")) 
        + "_ML."+ diachi.substring(diachi.lastIndexOf(".")+1);
    File anhDaXuLy = new File(dc);
    try {
        ImageIO.write(anhHoanTat,diachi.substring(diachi.lastIndexOf(".")+1), anhDaXuLy);
    } catch (IOException e) {
        ui.warningSave();
    }
    ui.hoanTat(dc);
}

除了没有捕获IOException之外,一切正常。系统显示错误,FileNotFoundException,据我所知,异常也是IOException

系统显示的屏幕截图:

Screenshot of what the system showed

然后我试着抓住确切的catch (FileNotFoundException e),但是Eclipse会让我把它改回IOException

Eclipse提示我的截图:

Screenshot of what Eclipse prompted me

Screenshot of what Eclipse prompted me

(它告诉我FileNotFoundException已经被IOException抓住了,所以最终我不得不删除它,这几乎可以追溯到我开始的地方。)

注意:之后我添加了NullPointerException并且代码抓住了它,但仍然没有抓住IOException catch (NullPointerException | IOException e)

系统显示的屏幕截图:

Screenshot of what the system showed

1 个答案:

答案 0 :(得分:1)

如果你正确地捕获了异常,你打印它(我假设你在ui.warningSave();方法上做了什么)会发生什么,但是你不会停止你的方法(或者return,exit,throw exception)所以程序到达catch(ui.hoanTat(dc);

之后的最后一行

eclipse的编译错误告诉你:

ImageIO.write()抛出IOException后,您无法仅抓住FileNotFoundException,因为它并未涵盖所有情况。

此外,编写catch (FileNotFoundException | IOException e)也是错误的,因为FileNotFoundException是多余的 - 它在扩展它时已经被IOException覆盖了。

相关问题