while True: try: # 代码块,逻辑 inp = input('Please enter number:') i = int(inp) except Exception as e: # e是Exception对象,对象中封装了错误信息 # 上述代码块如果出错,自动执行当前块的内容 i = 1 print(i)
异常处理流程
try: # li = [11,222] # li[999] int('w3r') except IndexError as e: print(e) except ValueError as e: print('ValueError',e) except Exception as e: print('Exception',e) else: print('else') finally: print('-----')
主动触发异常 try: # int('efdsf' # 主动触发异常) raise Exception('不过了...') except Exception as e: print(e)
主动触发异常
自定义异常
断言