0

我正在尝试将一个python 类重构为 Genie,但我对如何处理错误感到困惑。一些指针将不胜感激。

如果我理解正确的话,使用 Genie 处理错误的方法是使用 Try...except 块,但是如何将以下类型的错误处理转换为这种范例:

# 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

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

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

这是一个虚拟代码,我只是对问题进行建模,我知道它不会按原样编译。我只是在寻找有关如何从 python 转换 '''raise''' 命令的指针。

4

1 回答 1

2

您需要将错误类型定义为 anexception然后确定您的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()如果您稍后需要调试,调用将记录超出范围索引的一些详细信息。

于 2016-07-17T11:23:38.440 回答