""" 运行结果为: Traceback (most recent call last): File "/Users/zachary/PycharmProjects/Python教程阶段1/code_oop/41什么是异常.py", line 6, in <module> print(varlist[3]) IndexError: list index out of range 其中: IndexError 异常类 list index out of range 异常信息 """
# 异常处理除法 val = input("请输入一个数字:") try: num = int(val) res = 10 / num print(res) except ValueError as e: print("not input number value") except ZeroDivisionError as e: print("can not input 0")
# 异常处理文件 try: withopen('./user.txt', 'r') as file: res = file.read() print(res) except: print('file not exist')
print('other program') # file not exist # other program
# 1.处理指定的异常,引发了非指定的异常,无法处理 try: varlist = [1, 2, 3] print(varlist[3]) except IndexError as e: print(e) # list index out of range
# 2.多分支处理异常 try: s = 'duanduan' res = int(s) except ValueError as e: print('ValueError', e) except KeyError as e: print('KeyError', e) except IndexError as e: print('IndexError', e) # ValueError invalid literal for int() with base 10: 'duanduan'
# 3.通用异常类 Exception try: s = 'duanduan' res = s[10] except Exception as e: print('Exception', e) # Exception string index out of range
# 4.多分支异常类+通用异常类 try: s = 'duanduan' res = int(s) except KeyError as e: print('KeyError', e) except IndexError as e: print('IndexError', e) except Exception as e: print('Exception', e) # Exception invalid literal for int() with base 10: 'duanduan'
# 5.try except else try: s = 'duandaun' res = str(s) except KeyError as e: print('KeyError', e) except IndexError as e: print('IndexError', e) except Exception as e: print('Exception', e) else: print('try中没有错误') # try中没有错误
# 6.try except else finally try: s = 'duandaun' res = str(s) except KeyError as e: print('KeyError', e) except IndexError as e: print('IndexError', e) except Exception as e: print('Exception', e) else: print('try中没有错误') finally: print('代码执行完毕,这句肯定输出') # try中没有错误 # 代码执行完毕,这句肯定输出