发生异常时继续我的申请

hgu*_*ser 1 java exception

代码:

String[] logs={"a","b","c"};
int errors=0;
for(String str:logs){
  try{
    LogParser.parse(str);
  } catch(ParseException e){
    error++;
    continue;  // Seems that, this two line codes are not reached.
  }
}
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,LogParser用于解析组合模式的tomcat日志,当获取日期格式数据时,我使用SimpleDateFormat将其解析为Java.Util.Date对象,然后它可能抛出一个ParseException.the logs数组这里只用于抛出异常.

但是,当解析一个日志时出现此异常时,应用程序将退出,我希望它继续下一个日志.

怎么做?

我已经阅读了以下教程:

http://download.oracle.com/javase/tutorial/essential/exceptions/catchOrDeclare.html.

它说Error和RuntimeException不是try catch块的子主题,应用程序无论如何都会退出.

但java.text.ParseException扩展了Exception,为什么它不能受我的try-catch块的约束?由于"错误"变量不是+1,

我曾想过用这个:

finally{
  error++;
  continue;
}
Run Code Online (Sandbox Code Playgroud)

是的,它可以工作,但是当正确解析日志时,错误也会添加,它不应该.

谁能告诉我为什么?

Ale*_*lex 5

你正在捕捉ParseException,但可能抛出另一种异常类型.尝试替换它,(Exception e)看看你扔的是什么类型.然后,您可以将catch的范围缩小到适当的异常类型.

String[] logs={"a","b","c"};
int errors=0;
for(String str:logs){
  try{
    LogParser.parse(str);
  } catch(Exception e){ // <-- try this
    error++;
    continue;
  }
}
Run Code Online (Sandbox Code Playgroud)