2010-10-19 81 views
1

的代码继续我的应用程序:当发生异常

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. 
    } 
} 

在上面的代码中,LOGPARSER的用于分析相结合模式的Tomcat的日志,当获取日期格式的数据,我用的是SimpleDateFormat的解析它到一个Java.Util.Date对象,那么它可能会抛出一个ParseException.the日志数组这里只是用于抛出异常。

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

如何制作它?

我已经阅读教程:

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

它表示Error和RuntimeException不是主try try块,应用程序将退出。

但java.text.ParseException扩展了Exception,为什么它不能服从我的try-catch块? 由于“错误”变量不要+1,

我也想过用这个:

是的,它的工作原理,但是当日志被正确解析,错误将还可以添加,它不应该。

任何人都可以告诉我为什么吗?

+0

你确定它是一个ParseException吗?应用程序退出时应该包含堆栈跟踪,包括异常类名称。 – Thilo 2010-10-19 01:42:56

+0

您使用哪种LogParser?检查它的文档或源代码,如果你有权限查看它是否在异常时用System.exit()退出。 – 2010-10-19 02:12:21

回答

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; 
    } 
} 
+0

或捕获Throwable来代替调试目的... – pstanton 2010-10-19 02:16:29

+0

但仅用于调试目的!从来没有抓住其他方面的Throwable;如果你做了 – naiad 2010-10-19 02:52:31

+0

就可以得到一些令人讨厌的错误。在找出问题后,您需要将范围缩小到我刚才提到的适当类型。 – Alex 2010-10-19 02:53:46

3

Alex是正确的。该计划正在抛出一种不同类型的例外情况,而不是您想要捕捉的ParseException。然而,不要捕捉Exception e,你可以尝试捕捉多个例外,从最具体的开始。例如:

String[] logs={"a","b","c"}; 
    int errors=0; 
    for(String str:logs){ 
     try{ 
     LogParser.parse(str); 
     } catch(ParseException e){ 
     error++; 
     continue; 
     } 
     catch(Exception e){ 
     //Code to catch generic exception 
     } 
    } 

你可以有很多的catch语句,只要你想,但请记住,匹配将被如此使用的第一个不把catch(Exception e)第一。