# 异常的使用
a = [1, 2, 3, 4, 5, 6, 0, 8, '22']# b = [item for item in a if 100 % item == 0]
# print(b) # 直接运行报错ZeroDivisionError: integer division or modulo by zero
# 因为在列表a中,0不能作为除数try: # 下面写可能包含错误的语句c = [item for item in a if 100 % item == 0]print(c)
except: # 出错就执行下面的语句print("出错") # 出错# 如果要报告出错误的类型try: # 下面写可能包含错误的语句d = [item for item in a if 100 % item == 0]print(d)
except ZeroDivisionError: # ZeroDivisionError表示0作为除数出错print("0不能作为除数") # 0不能作为除数# 但是此种方法只能捕捉0作为除数的异常,后面的字符串无法捕捉a0 = [1, 2, 3, 4, 5, 6, 9, 8, '22']
try: # 下面写可能包含错误的语句e = [item for item in a0 if 100 % item == 0]print(e) # 出错TypeError: unsupported operand type(s) for %: 'int' and 'str'
except ZeroDivisionError: # ZeroDivisionError表示0作为除数出错print("0不能作为除数") # 0不能作为除数
except TypeError: # TypeError用来报告数据类型的错误print("数据类型错误") # 数据类型错误# 以上的方法都只能针对性的报告错误
# 我们写程序往往不能知道可能出错的原因
# 不能通过穷举法列出所有错误的可能
# 所以建议按照如下方法提取程序的异常a0 = [1, 2, 3, 4, 5, 6, 9, 8, 'x1']
try: # 下面写可能包含错误的语句e = [item for item in a0 if 100 % item == 0]print(e) # 出错TypeError: unsupported operand type(s) for %: 'int' and 'str'
except ZeroDivisionError: # 列出预计的第一个错误异常print("0不能作为除数") # 0不能作为除数
except TypeError: # 列出预计的第二个错误异常print("数据类型错误") # 数据类型错误
except Exception: # 没有指定异常类或指定为“异常”,如果以上两种错误都不是,就执行以下语句print("其他未知错误")print("完成") # 完成