簡體   English   中英

IIOException 無法到達的 catch 塊。 try 語句和 javax.imageio.IIOException: Can't read input file 永遠不會拋出此異常

[英]Unreachable catch block for IIOException. This exception is never thrown from try statement and javax.imageio.IIOException: Can't read input file

觸發“IIOException 的無法到達的 catch 塊。此異常永遠不會從 try 語句中引發”的代碼

        int width = 0, height = 0;
        BufferedImage img = null;
        try {
            try {
                img = ImageIO.read(new File("target.png"));
                String imgpath = "target.png";
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (javax.imageio.IIOException e) {
            try {
              img = ImageIO.read(new File("target.jpg"));
                String imgpath = "target.jpg";
            } catch (IOException f) {
                f.printStackTrace();
            }
        } finally {
            if (img != null) {
                width = img.getWidth();
                height = img.getHeight();
            }
        }

所以我刪除了涉及錯誤的 catch 語句:

        try {
            try {
                img = ImageIO.read(new File("target.png"));
                String imgpath = "target.png";
            } catch (IOException e) {
                e.printStackTrace();
            }
        } finally {
            if (img != null) {
                width = img.getWidth();
                height = img.getHeight();
            }
        }

現在它觸發了它說不會觸發的錯誤:“javax.imageio.IIOException:無法讀取輸入文件!”

我究竟做錯了什么

你讓這變得比它需要的更復雜。

只需檢查第一個文件是否存在:

File imageFile = new File("target.png");
if (!imageFile.canRead()) {
    imageFile = new File("target.jpg");
}

try {
    img = ImageIO.read(imageFile);
} catch (IOException e) {
    throw new RuntimeException("Couldn't read target.png or target.jpg", e);
}

除非您真的相信您的應用程序在沒有該圖像的情況下會正常顯示和運行,否則在捕獲該異常(以及大多數異常)時正確的操作過程是通過讓異常傳播來停止您正在執行的操作。 將它包裝在另一個異常中通常是一種有效的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM