BudsNanKis BudsNanKis - 6 months ago 11
Java Question

Why is Matcher.group() throwing illegal state exception?

Why does the below code work fine

Matcher reg = Pattern.compile("(A|B)\\w{2}(C|D)").matcher("");
while ((line=reader.readLine()) != null)
{
if (!loading || reg.reset(line).matches())
{
if (reg.reset(line).matches()) {
String id = reg.group(1);
}
}
}


but

while ((line=reader.readLine()) != null)
{
if (!loading || reg.reset(line).matches())
{
String id = reg.group(1);
}
}


throws IllegalSyntaxException?

I was surprised because I am already calling matches in the if condition. The expectation is that it returns the string matching the group, throws the exception instead.

java.lang.IllegalStateException: No match found


What am I missing?

Answer

If loading == false, reg.reset(line).matches() won't be executed, because !loading already is true. In your first example you then "again" check if there is a match and only then try to get the group. In your second example, you just assume that there is a match because you got there, which may not be true.

If the code you posted is all you do in this if-statement, you may get rid of the !loading check, as it doesn't matter if it's true or false - as soon as you find a match, you'll execute the code within the body, if you cannot find a match, it won't be executed.

Comments