我正在寫一個文件讀取器,返回一個對象,我希望它警告解析錯誤並繼續下一個記錄。錯誤處理中的遞歸?
下面的代碼是這個的明顯實現,但涉及從catch塊內部遞歸。有沒有技術或文體原因不這樣做?
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();
}
}
}
問題在於你的程序會在每個錯誤的記錄中累積堆棧空間,這使得它很容易受到攻擊。例如,當這段代碼成爲Web服務的一部分時,攻擊者只能提供許多錯誤記錄,直到整個服務從堆棧溢出中死亡。這將是一次成功的拒絕服務攻擊。 – Ingo 2011-05-06 12:46:55
@Ingo謝謝,這應該是一個答案:-)。 – 2011-05-06 12:47:43