try: # 正常程序 ipt = input("请输入:") num = int(ipt) #ValueError print(num) except Exception as e: # 一旦有异常,执行except内部块 print(e) num = 1 print(num) 请输入:1.5 invalid literal for int() with base 10: '1.5' 1
列表
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
try: # li = [2 , 3] # li[2] # IndexError
a = 2 b = 0 c = a/b # ZeroDivisionError except IndexError as e: print(e) except ZeroDivisionError as e: print(e) except Exception as e: print(e) else: print("如果没错~执行else代码") finally: print("不管有无异常都执行")
抛出异常raise
1 2 3 4 5 6 7 8 9 10 11 12
''' 主动抛出异常 ''' deftest(time): if time<5: raise Exception("错误") try: test(4) except Exception as e: print(e) else: print("成功")
评论