我在处理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