简体   繁体   English

在ANTLR4中处理自定义异常

[英]Handling custom exception in ANTLR4

I have a grammar that parses URIs in the lexer and then constructs a java.net.URL from them in a grammar action. 我有一个语法,该语法分析词法分析器中的URI,然后在语法操作中从它们构造一个java.net.URL。 The lexer can accept strings that might not be legal URLs so I'd like to intelligently handle URISyntaxExceptions if they get thrown. 词法分析器可以接受可能不是合法URL的字符串,因此,如果抛出异常,我想智能地处理URISyntaxExceptions。

I'm new to ANTLR 4 (but spent some time with ANTLR 3) and just want to know the best practice for handling such exceptions in 4. 我是ANTLR 4的新手(但是花了一些时间在ANTLR 3上),只是想知道在4中处理此类异常的最佳实践。

Here's a code snippet from the grammar: 这是语法的代码段:

iri returns [IRI term] :
    IRIREF 
    { $term = spt.getIRI($IRIREF.text); } |
    prefixedName
    ;

'spt' is a support object I set with a parameter to the start rule. “ spt”是我用开始规则的参数设置的支持对象。 The method 'getIRI' can throw the java.net.URISyntaxException . 方法“ getIRI”可以引发java.net.URISyntaxException I would like a graceful way to handle this locally in the rule, terminate the parse (or do something else), but don't know where to attach a catch block. 我想以一种优美的方式在规则中本地处理,终止解析(或执行其他操作),但是不知道在何处附加catch块。

The documentation covers the basics of catching errors and the implementation of error strategies. 文档涵盖了捕获错误和错误策略的实现的基础。 The Definitive ANTLR 4 Reference covers both topics in much more detail. 权威ANTLR 4参考书更详细地介绍了这两个主题。

Update: 更新:

The actual grammar specification (from ANTLRv4Parser.g4) for a 'rule' is “规则”的实际语法规范(来自ANTLRv4Parser.g4)为

parserRuleSpec
  : DOC_COMMENT?
    ruleModifiers? RULE_REF ARG_ACTION?
    ruleReturns? throwsSpec? localsSpec?
    rulePrequel*
    COLON
    ruleBlock
    SEMI
    exceptionGroup
  ;

(In relevant part, this is the same as the 'rule' spec in ANTLRParser.g, which is the actual grammar used to build compiler tool present in the Antlr v4 jar.) (在相关部分,这与ANTLRParser.g中的“规则”规范相同,后者是用于构建Antlr v4 jar中存在的编译器工具的实际语法。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM