我一直在寫我的個人圖書館,我一直在努力實現這個代碼,我在其他程序中使用:因爲這段代碼被添加到庫如何處理例外的定製庫
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)
接近某些作品。但是,有一些反對從構造函數中拋出異常的參數。將對象實例與讀取/檢索圖像的調用分開可能更好,並添加'getImage(String imgpath)拋出IOException'方法。 – KevinO