我正在编写一个返回对象的文件读取器,我希望它能够警告解析错误并继续处理下一条记录。
下面的代码是此代码的明显实现,但涉及从 catch block 内部递归。有什么技术或风格上的理由不这样做吗?
public RecordType nextRecord() throws IOException{
if (reader == null){
throw new IllegalStateException("Reader closed.");
}
String line = reader.readLine();
if (line == null){
return null;
}else{
try {
return parseRecord(line);
}catch (ParseException pex){
logger.warn("Record ignored due to parse error: "
+ pex.getMessage());
//Note the recursion here
return nextRecord();
}
}
}
最佳答案
我更喜欢使用循环。通过递归,您永远不知道可以安全地走多深。
String line;
while((line = reader.readLine()) != null) {
try {
return parseRecord(line);
}catch (ParseException pex){
logger.warn("Record ignored due to parse error: " + pex);
}
}
return null;
关于java - 错误处理中的递归?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5911557/