2017-11-25 291 views
1

這是一個圖像處理應用程序。我在下面顯示的代碼是用於創建一個圖像文件並將完整處理的BufferedImage保存到它。嘗試創建映像文件時,try-catch無法捕獲IOException

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和代碼抓住它,但還是沒有趕上什麼系統顯示IOExceptioncatch (NullPointerException | IOException e)

截圖:

Screenshot of what the system showed

回答

1

會發生什麼事是你正確捕獲異常,你打印出來(我假設這就是你在ui.warningSave();方法中所做的),但是然後你不停止你的方法(或者返回,退出,拋出異常),所以程序到達最後一行後,catch(ui.hoanTat(dc);

編譯錯誤日食sho請你:

因爲ImageIO.write()拋出IOException,你不能只捕獲FileNotFoundException,因爲它不包括所有情況。

此外,編寫catch (FileNotFoundException | IOException e)也是錯誤的,因爲FileNotFoundException是多餘的 - 它在擴展它時已經被IOException覆蓋。

+0

雖然仍然無法正常工作。 –

相關問題