异常处理
异常捕获
-
try-expect
语句i = input("请输入一个非零十进制数: ") y = 123 try: result = y / int(i) print(result) print("{0} / {1} = {2}".format(y, i, result)) except ZeroDivisionError as e1: print("异常: {}".format(e1)) except ValueError as e2: print("异常: {}".format(e2)) # 多重异常捕获, 合并相同的处理: # except (ZeroDivisionError, ValueError) as e: # print("异常: {}".format(e)) # # 最后省略异常类型的except代码块用来捕获上面没有匹配的异常类. # except: # print("某种异常") finally: # 释放资源 print("资源释放...")
-
语句嵌套
i = input("请输入一个非零十进制数: ") y = 123 try: i2 = int(i) try: result = y / i2 print("{0} / {1} = {2}".format(y, i2, result)) except ZeroDivisionError as e2: print("异常: {}".format(e2)) except ValueError as e1: print("异常: {}".format(e1)) finally: # 释放资源 print("资源释放...")
自定义异常类
class CE(Exception):
def __init__(self, message):
super().__init__(message)
手动引发异常
-
raise
class CE(Exception): def __init__(self, message): super().__init__(message) i = input("请输入一个非零十进制数: ") y = 123 try: result = y/int(i) print("{0} / {1} = {2}".format(y, i, result)) except ZeroDivisionError as e1: raise CE("除数为零!") except ValueError as e2: raise CE("无效数字!") # 请输入一个非零十进制数: 0 # Traceback (most recent call last): # File "F:\day12_.py", line 10, in <module> # result = y / int(i) # ZeroDivisionError: division by zero # # During handling of the above exception, another exception occurred: # # Traceback (most recent call last): # File "F:\day12_.py", line 13, in <module> # raise CE("除数为零!") # __main__.CE: 除数为零!