2016-04-01 23 views
0

我一直在寫我的個人圖書館,我一直在努力實現這個代碼,我在其他程序中使用:因爲這段代碼被添加到庫如何處理例外的定製庫

public ImagePanel(String imgpath) { 
    try { 
     image = ImageIO.read(new File(imgpath)); 
    catch (IOException e) { 
     // handle exception 
    } 
} 

,我想要處理在我使用這個新代碼中的異常。

這是我應該如何正確地將相同的代碼實現到我的庫?

public ImagePanel(String imgpath) throws IOException { 
    image = ImageIO.read(new File(imgpath)); 
} 

這就是我如何在其他程序中使用我的庫?

import testlib.ImagePanel; 
ImagePanel boardPanel = null; 
try { 
    ImagePanel boardPanel = new ImagePanel("imageexample.png"); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 
// do stuff here (boardPanel is "null" above because I've gotten an error that it's not initialized as I do that in the try/catch block) 
+3

接近某些作品。但是,有一些反對從構造函數中拋出異常的參數。將對象實例與讀取/檢索圖像的調用分開可能更好,並添加'getImage(String imgpath)拋出IOException'方法。 – KevinO

回答

0

的最佳方式來處理它IMO將包裹IOException異常錯誤(即new Error(e)並拋出錯誤。同樣,國際海事組織,這是合理的,因爲該文件是有或沒有真正需要的運行時,不編譯時間修復。而這樣一來,你就不必聲明構造函數中的異常,像

public ImagePanel(String imgpath) { 
    try { 
    image = ImageIO.read(new File(imgpath)); 
    } 
    catch (IOException e) { 
    throw new Error(e); 
    } 
} 
+0

或使用'RuntimeException'也是未選中的。 – fgb

+0

你會如何建議包裝IOException?在我的圖書館代碼中捕捉它並拋出一個'新的錯誤'? – Aaron

+0

@Aaron我已經更新了我的回答,以顯示我該怎麼做 – ControlAltDel

-1

如果發生異常時,您可以返回空值。它不會引起程序崩潰。

但當你拋出異常時,它可能會崩潰前衛如果用戶不「捕捉」它,則爲ram。

public ImagePanel(String imgpath) throws IOException{ 
try { 
    image = ImageIO.read(new File(imgpath)); 
catch (IOException e) { 
    // handle exception 
    throw new IOException(); 
    } 
}