我正试图将一个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我现在所处的代码看起来(在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这是一个虚拟代码,我只是对问题建模,我知道它不会按原样编译。我只是在寻找一个指针,说明如何从python中传递‘’am‘’“命令。
发布于 2016-07-17 11:23:38
您需要将错误类型定义为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
)精灵是静态类型的,所以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()的调用将记录超出边界索引的一些细节。
https://stackoverflow.com/questions/38416870
复制相似问题