我有类似下面的情况:
/** Get a list of records */
public ArrayList<Record> foo() throws BazException{
// Create the list
static ArrayList<Record> records = new ArrayList<Record>();
// Use MyLibrary to load a list of records from the file
String str = SomeoneElsesLibrary.loadData(new File("mydata.dat"), new DataLoader(){
// will be called once for each record in the file
String processRecord(Record r){
// if there's no "bar", invalid record
if( ! r.hasField("bar") ){
throw new BazException();
}
records.add(r);
}
});
return records;
}
显然这不起作用,因为 SomeoneElsesLibrary
不知道什么是 BazException
。我也不能说 processRecord() throws BazException
因为那样原型(prototype)将不再匹配。我开始认为我的这个实现的整体结构是错误的。 (我正从 Node.JS 瘾中恢复过来,必须重新学习 一些 大多数 Java 模式。)我将如何重构我的代码以使其更符合 Java 的习惯?
伪代码很好,甚至只是描述。另外,不要觉得您需要使用匿名内部类,就像我第一次尝试那样;我只是在寻找“Java 方式”来做到这一点。
最佳答案
Ryan,确保您的 BazException 是 RuntimeException(未经检查的异常)而不是 Exception(已检查的异常)的扩展。
否则,您可能已经注意到,编译器会提示没有处理您自己的异常。
有关更多信息,请查看有关未检查异常(即 RuntimeException 或 Error)的一些信息:
http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html
关于java - 处理匿名内部类中的新异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18816197/