异常处理

1.异常处理

import traceback
a = []
d = {}
try:
    1 / 0
    # a[1]
    # d["abc"]
except Exception as e:
    # traceback.print_exc() #只是print
    print(traceback.format_exc()) #错误的那坨字符串
# except ZeroDivisionError as e:
#     print(e)
#     print("出错了")
# except IndexError as e:
#     print(e)
# except KeyError as e:
#     print(e)
else:
    print("不出错的情况下走这里")
finally:
    print("什么时候会执行呢?")#任何时候都会执行

 

2.主动抛出异常

import sys
v = sys.version_info[0]
v2 = sys.version_info[1]
# print(v)
# print(v2)
if v ==3 and v2>=5:
    pass
else:
    raise Exception("python版本不正确,请使用3.5以上的python版本")

 

posted @ 2021-02-11 16:42  chenghuahua  阅读(25)  评论(0编辑  收藏  举报