首页 > 解决方案 > python在if语句中引发异常

问题描述

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

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

你能帮我修一下吗?

标签: pythonexception

解决方案


如果你想让你的函数抛出一个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))

但这取决于你。


推荐阅读