python - 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
你能帮我修一下吗?
解决方案
如果你想让你的函数抛出一个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))
但这取决于你。
推荐阅读
- python - 如何将 Python 源代码拆分为令牌?
- vue.js - 如何使用 vue-test-utils 打开 bootstrap-vue 模态?
- c++ - 为什么在基于 SFINAE 的反射中会发生这种替换失败?
- haskell - 为什么使用具有重叠实例的类型类的此函数在 GHCi 中表现不同?
- pandas - 使用 pandas 转换日期时间
- html - 底部的页脚,仅在向下滚动超过正文元素/超过窗口高度的 100% 时可见?
- javascript - ES5 中的块作用域
- sql - 连接查询适用于 mysql 但不适用于 java
- javascript - 错误 - 简单的加密和解密 - Node.js
- typescript - 将泛型类型属性过滤到特定类型