Java 我可以在不切换到显式迭代器的情况下为每个循环处理异常吗?
我使用的课程如下:Java 我可以在不切换到显式迭代器的情况下为每个循环处理异常吗?,java,for-loop,exception,foreach,exception-handling,Java,For Loop,Exception,Foreach,Exception Handling,我使用的课程如下: try( SamReader reader = SamReaderFactory.makeDefault().open(new File(filename)) ){ for(SAMRecord record : reader){ // potential exception here, based on file input // process record } } catch(SAMFormatException e){ /
try(
SamReader reader = SamReaderFactory.makeDefault().open(new File(filename))
){
for(SAMRecord record : reader){ // potential exception here, based on file input
// process record
}
}
catch(SAMFormatException e){
// rest of loop is skipped by handling exception here
}
SamReader类基本上从文本文件读取数据,并从文本文件中的每一行生成一个新的SAMRecord。SamReader类对文件中的每一行执行检查,并可以引发运行时SAMFormatException。我可以处理这个异常,但我还没有找到一种方法来处理foreach循环,同时仍然试图处理文件的其余部分
在使用for each循环格式并继续处理文件的其余部分时,是否有方法处理运行时异常?或者我需要显式地使用迭代器来控制它吗 将试捕器放入循环中
或者——正如您所解释的,异常是在迭代时引发的——您使用了一种更低的api方式iterator()
Iterator it=reader.Iterator()
while(it.hasNext()){
试一试{
SAMRecord=it.next();
//过程记录
}捕获(SAMFORMATE异常){
//你在这里经手吗
}
}
这不起作用,因为异常是在生成SAMRecord记录时抛出的,而不是在处理它时抛出的。@mattm为解决方案草图添加了一个带有迭代器库的解决方案,但实际上我更感兴趣的是,对于for each循环,这种异常处理是否可行,或者迭代器方法是否必要。
SamReader reader = SamReaderFactory.makeDefault().open(new File(filename));
for(SAMRecord record : reader){
try {
// process record
} catch(SAMFormatException e) {
// handle exception
}
}
Iterator<SAMRecord> it = reader.iterator()
while(it.hasNext()) {
try {
SAMRecord record = it.next();
// process record
} catch(SAMFormatException e) {
// do handling here
}
}