Why is .NET exception not caught by try/catch block?

前端 未结 25 730
Happy的楠姐
Happy的楠姐 2020-12-04 19:24

I\'m working on a project using the ANTLR parser library for C#. I\'ve built a grammar to parse some text and it works well. However, when the parser comes across an illeg

25条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-04 19:47

    Steve Steiner is correct that the exception is originating in the antlr library, passing through the mTokens() method and being caught in the antlr library. The problem is that this method is auto-generated by antlr. Therefore, any changes to handle the exception in mTokens() will be overwritten when your generate your parser/lexer classes.

    By default, antlr will log errors and try to recover parsing. You can override this so that the parser.prog() will throw an exception whenever an error is encountered. From your example code i think this is the behaviour you were expecting.

    Add this code to your grammer (.g) file. You will also need to turn off "Enable Just My Code" in the debugging menu.

    @members {
    
        public override Object RecoverFromMismatchedSet(IIntStream input,RecognitionException e,    BitSet follow)  
        {
            throw e;
        }
    }
    
    @rulecatch {
        catch (RecognitionException e) 
        {
            throw e;
        }
    }
    

    This is my attempt at a C# version of the example given in the "Exiting the recogniser on first error" chapter of the "Definitive ANTLR Reference" book.

    Hope this is what you were looking for.

提交回复
热议问题