python在if语句中引发异常

时间:2019-04-24 08:20:44

标签: python exception

我想测试对象名称中是否有某些字符串,并根据它返回路径名称。如果未找到任何内容,我想抛出一个错误。 这是我的代码:

def object_path(object_name):
    try:
        if object_type(object_name) in ['JX', 'JW', 'MT', 'WF']:
            obj_path = 'task'
        elif object_type(object_name) in ['TT', 'MT', 'FT']:
            obj_path = 'trigger'
        elif object_type(object_name) == 'VR':
            obj_path = 'virtual'
        else:
            raise ValueError()
    except ValueError as err:
        print('The name of  object {} is 
           incorrect'.format(object_name))
    return obj_path

if __name__ == "__main__":

    x = object_path('L8H_gh_hgkjjkh')
    print (x)

这似乎不正确,这就是让我退缩的原因:

The name of UAC object L8H_gh_hgkjjkh is incorrect
Traceback (most recent call last):
  File "uac_api_lib.py", line 29, in <module>
    x = object_path('L8H_gh_hgkjjkh')
  File "uac_api_lib.py", line 24, in object_path
    return obj_path
UnboundLocalError: local variable 'obj_path' referenced before assignment

您能帮我解决吗?

2 个答案:

答案 0 :(得分:3)

如果您希望函数抛出ValueError,请不要在函数中捕获它。

def object_path(object_name):
    if object_type(object_name) in ['JX', 'JW', 'MT', 'WF']:
        obj_path = 'task'
    elif object_type(object_name) in ['TT', 'MT', 'FT']:
        obj_path = 'trigger'
    elif object_type(object_name) == 'VR':
        obj_path = 'virtual'
    else:
        raise ValueError('The name of object {} is incorrect'.format(object_name))
    return obj_path

此外,您可以像这样简化它:

def object_path(object_name):
    otype = object_type(object_name)
    if otype in {'JX', 'JW', 'MT', 'WF'}:
        return 'task'
    if otype in {'TT', 'MT', 'FT'}:
        return 'trigger'
    if otype == 'VR':
        return 'virtual'
    raise ValueError('The name of object {} is incorrect'.format(object_name))

但这取决于您。

答案 1 :(得分:0)

“赋值之前被引用”错误是因为obj_path仅存在于try / except块内。只需在此之前定义它即可。

def object_path(object_name):
    obj_path = ""
    try:
        if object_type(object_name) in ['JX', 'JW', 'MT', 'WF']:
            obj_path = 'task'
        elif object_type(object_name) in ['TT', 'MT', 'FT']:
            obj_path = 'trigger'
        elif object_type(object_name) == 'VR':
            obj_path = 'virtual'
        else:
            raise ValueError()
    except ValueError as err:
        print('The name of  object {} is 
           incorrect'.format(object_name))
    return obj_path