tags:

views:

70

answers:

2

The codes:

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

In the above codes, the LogParser used to parse the tomcat log of combined pattern,when get the date format data, I use the SimpleDateFormat to parse it to a Java.Util.Date object, then it may throw a ParseException.the logs array here is just used for throwing the exception.

However when this exception ouccur while parsing one log, the app will exit ,I want it contine the next log.

How to make it?

I have read the tutorial at :

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

It said that the Error and RuntimeException are not subjec to the try catch block, the app will exit anyway.

But the java.text.ParseException extends the Exception,why it can not be subject to my try-catch block? Since the "error" variable do not be +1,

I have thought use this:

finally{
  error++;
  continue;
}

yes, it works,but when the log is correctly parsed,the error would be add also,it should not be.

Can any one tell me why?

+5  A: 

You are catching ParseException, but probably another exception type is thrown. Try to replace this with (Exception e) and see what type you're throwing. Then you can reduce the scope of the catch to the appropriate exception type.

String[] logs={"a","b","c"};
int errors=0;
for(String str:logs){
  try{
    LogParser.parse(str);
  } catch(Exception e){ // <-- try this
    error++;
    continue;
  }
}
Alex
or catch Throwable instead for debugging purposes ...
pstanton
but only for debugging purposes! never catch Throwable elsewise; you could get some nasty bugs down the road if you do
Vuntic
That's right. After figuring out the problem you need to narrow the scope to the appropriate type like I mentioned.
Alex
Thanks, alex is right, thank you. The ParseException would be thrown by the SImpleDateFormat while meet a error, In my example, the exception must be some exception defined in the regular package. Thanks again.
hguser
+3  A: 

Alex is correct. The program is throwing a different type of exception and not the ParseException you are trying to catch. However instead of catching Exception e you could try to catch multiple exceptions starting with the most specific. For example:

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

You can have as many catch statements as you want, but remember that the first one that matches will be used so do not put catch(Exception e) first.

Slruh