开发者

is there a way to handle all antlr exception types in a rule catch[...] block

I'm using ANTLR3 with the C runtime.

I'd like to do some custom error handling. What I'm really after is that if there is an antlr matching exception of any kind in a sub rule I'd like to tell ANTLR to skip trying to handle it and let it percolate up to a more global rule.

At that rule I'll log it and then try to resume.

I've set the rule catch method like so, so that all rules won't try to recover.

@rulecatch 
{
    if (HASEXCEPTION())
    {
    PREPORTERROR();
    }
}

This allows me to insert catch handlers on the rules that i want.

At my rule of interest i can then use the catch syntax like so:

catch [ANTLR3_RECOGNITION_EXCEPTION]
{
    PREPORTERROR();
    RECOGNIZER->consumeUntil(RECOGNIZER,RCURLY);
    CONSUME();
    PSRSTATE->error = ANTLR3_FALSE;
    PSRSTATE->failed = ANTLR3_FALSE;
     }

The problem is that this syntax seems to only allow me to catch one type of exception. I'd like to be able to catch all exception types.

Is there a way to do this?

I thought I could overload all the recovery functions but then some code generates exceptions like so:

                    CO开发者_JAVA技巧NSTRUCTEX();
                    EXCEPTION->type         = ANTLR3_NO_VIABLE_ALT_EXCEPTION;
                    EXCEPTION->message      = (void *)"";
                    EXCEPTION->decisionNum  = 23;
                    EXCEPTION->state        = 0;


                    goto rulewhenEx;

which means I'll need to catch all possible exceptions.

Any thoughts??


I've ended up trying two solutions for this.

Approach 1)

Overloading the rulecatch setting to set the exception type to one specific type

@rulecatch 
{
    if (HASEXCEPTION())
    {

    // This is ugly.  We set the exception type to ANTLR3_RECOGNITION_EXCEPTION so we can always
    // catch them.
    PREPORTERROR();
    EXCEPTION->type = ANTLR3_RECOGNITION_EXCEPTION;
    }
}

This allows me to use one catch block as all exceptions will be of that type.

Approach 2)

I just use multiple catch blocks and they all dispatch to a common function to handle the error

catch [ANTLR3_RECOGNITION_EXCEPTION]
{
    handleException();
}
catch [ANTLR3_MISMATCHED_TOKEN_EXCEPTION]
{
    handleException();
}
....
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜