1. 主动抛出异常
1 import sys 2 v = sys.version_info[0] 3 v2 = sys.version_info[1] 4 # print(v) 5 # print(v2) 6 if v ==3 and v2>=5: 7 pass 8 else: 9 raise Exception("Python版本不正确,请使用3.5以上的python版本")
2. 异常处理
1 import traceback 2 a = [] 3 d = {} 4 try: 5 1 / 0 6 # a[1] 7 # d["abc"] 8 except Exception as e: 9 # traceback.print_exc() #只是print 10 print(traceback.format_exc()) #错误的那坨字符串 11 # except ZeroDivisionError as e: 12 # print(e) 13 # print("出错了") 14 # except IndexError as e: 15 # print(e) 16 # except KeyError as e: 17 # print(e) 18 else: 19 print("不出错的情况下走这里") 20 finally: 21 print("什么时候会执行呢?")#任何时候都会执行