使用Genie处理错误

时间:2016-07-17 00:31:49

标签: genie

我正在尝试将python class重构为精灵,但我仍然坚持如何处理错误。一些指示将非常感激。

如果我理解得当,Genie处理错误的方法是使用Try ...除了块,但是如何将以下类型的错误处理转换为这个范例:

# Enable dictionary/list-style access to options and arguments.
def __getitem__(self, key):
    if isinstance(key, int):
        if key < len(self.arguments):
            return self.arguments[key]
        else:
            raise ArgParserError(
                "positional argument index [%s] is out of bounds" % key
            )
    else:
        option = self._get_opt(key)
        return option.value

我现在的代码看起来像(在Genie中):

def getitem (key:int):string
    if key.is_int()
        if key < len(_arguments)
            return _arguments[key]
        else
            raise ArgParserError(
                "positional argument index [%s] is out of bounds", key
            )
    else
        var option = _get_opt(key)
        return option.value

这是一个虚拟代码,我只是对问题建模,我知道它不会按原样编译。我只想找到一个关于如何转换&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;来自python的命令。

1 个答案:

答案 0 :(得分:2)

您需要将错误类型定义为exception,然后确定您的getitem函数raises出现这样的错误:

exception ArgParserError
    OUT_OF_BOUNDS

def getitem( key:int ):string raises ArgParserError
    if key < len(_arguments)
        return _arguments[key]
    else
        raise new ArgParserError.OUT_OF_BOUNDS(
            "positional argument index [%s] is out of bounds", key
             )

Genie是静态类型的,因此if key.is_int()是不必要的。 Vala编译器将在编译时检查对getitem函数的所有调用都将整数作为参数传递。

另一种方法是对结果值使用out参数,并使用函数的返回值来表示结果是否有效:

def getitem( key:uint, out value:string ):bool
    result:bool = false
    value = ""
    if key < _arguments.length
        value = _arguments[ key ]
        result = true
    else
        info( "positional argument index [%s] is out of bounds", key )
    return result

通过使密钥为无符号整数uint,无法传递负索引。如果您需要稍后进行调试,对info()的调用将记录越界索引的一些细节。

相关问题