[antlr-interest] rethrowing of exceptions in ANTLR default exception handlers
Dennis Marsa
drm at xilinx.com
Thu Mar 21 14:03:34 PST 2002
Hello,
An ANTLR C++ default exception handler generally looks something
like this:
catch (RecognitionException& ex) {
if( inputState->guessing == 0 ) {
reportError(ex);
consume();
consumeUntil(_tokenSet_6);
} else {
throw ex;
}
}
When guessing, the handler re-throws the exception with
the "throw ex;" statement in the else clause.
"throw ex;" actually throws a copy of ex (even though ex
is a reference). If the caught exception is actually a
subclass of RecognitionException (e.g. MismatchedTokenException),
the copy made by the "throw ex" will only be a copy of the
RecognitionException part of the original exception.
Thus, the original exception can be sliced to a base class,
possibly losing information from the original exception, when
it is rethrown.
I believe the appropriate fix is to use throw with no operand:
throw; // no operand
which by definition rethrows the caught exception (ex)
without copying it.
catch (RecognitionException& ex) {
if( inputState->guessing == 0 ) {
reportError(ex);
consume();
consumeUntil(_tokenSet_6);
} else {
throw; // rethrows ex without copying
}
}
Attached is a patch against the 2.7.2a2 C++ code generator
that addresses this issue.
Regards,
Dennis
Your use of Yahoo! Groups is subject to http://docs.yahoo.com/info/terms/
-------------- next part --------------
*** CppCodeGenerator.java.orig Thu Mar 21 14:37:16 2002
--- CppCodeGenerator.java Thu Mar 21 14:37:31 2002
***************
*** 2267,2273 ****
println("} else {");
tabs++;
// When guessing, rethrow exception
! println("throw "+extractIdOfAction(handler.exceptionTypeAndName)+";");
tabs--;
println("}");
}
--- 2267,2273 ----
println("} else {");
tabs++;
// When guessing, rethrow exception
! println("throw;");
tabs--;
println("}");
}
***************
*** 3326,3332 ****
// When guessing, rethrow exception
println("} else {");
tabs++;
! println("throw ex;");
tabs--;
println("}");
}
--- 3326,3332 ----
// When guessing, rethrow exception
println("} else {");
tabs++;
! println("throw;");
tabs--;
println("}");
}
More information about the antlr-interest
mailing list