我在處理3個應該處理的異常時執行以下方法時遇到了一些麻煩。 我應該像我正在做的那樣包含try/catch塊嗎?還是應該爲應用程序而不是類設計?Java異常處理方法
的方法說我應該實現這個:
public Catalog loadCatalog(String filename)
throws FileNotFoundException, IOException, DataFormatException
此方法加載從目錄的產品指定的存檔的信息,並返回目錄。
從打開文件開始閱讀。然後繼續讀取並處理文件的每一行。
方法String.startsWith
被用於確定線路的類型:
- 如果線的類型是「產品」,該方法readProduct被調用。
- 如果行的類型是「Coffee」,則調用readCoffee方法。
- 如果行的類型是「Brewer」,則調用readCoffeeBrewer方法。
生產線處理後,loadCatalog
將產品(產品,咖啡或啤酒)添加到產品目錄。
當處理完文件的所有行時,loadCatalog
將產品目錄返回給進行調用的方法。
這種方法可以拋出以下例外:
FileNotFoundException
- 如果不存在指定的文件。IOException
- 如果讀取指定文件的信息時發生錯誤。DataFormatException
- 如果某行有錯誤(例外必須包含有錯誤的數據線)
這是我到目前爲止有:
public Catalog loadCatalog(String filename)
throws FileNotFoundException, IOException, DataFormatException{
String line = "";
try {
BufferedReader stdIn = new BufferedReader(new FileReader("catalog.dat"));
try {
BufferedReader input = new BufferedReader(
new FileReader(stdIn.readLine()));
while(! stdIn.ready()){
line = input.readLine();
if(line.startsWith("Product")){
try {
readProduct(line);
} catch(DataFormatException d){
d.getMessage();
}
} else if(line.startsWith("Coffee")){
try {
readCoffee(line);
} catch(DataFormatException d){
d.getMessage();
}
} else if(line.startsWith("Brewer")){
try {
readCoffeeBrewer(line);
} catch(DataFormatException d){
d.getMessage();
}
}
}
} catch (IOException io){
io.getMessage();
}
}catch (FileNotFoundException f) {
System.out.println(f.getMessage());
}
return null;
}
感謝偉大的忠告,但它聽起來像一個更好的設計技術來拋出僅1例外,處理所有的人。我從現在開始嘗試一下。但是,我忘了提及這個特定的練習(對於學校),我必須完全按照描述來實現該方法,因爲之後我必須通過預製Tesfile應用程序來運行它,並確保它編譯完成。 – edu222 2010-07-04 17:03:55