python 异常处理:
简单的异常处理主要依靠内置异常处理结构体,代码结构如下:
try:
…
except ValueError as e: # 异常判断,出现ValueError错误时处理机制
…
except ZeroDivisionError as e: # 异常判断,出现ZeroDivisionError错误时处理机制
…
finally:
…
示例:
# coding = utf-8
class Test:
def __init__(self, num):
self.num = num
def unnormal(self):
try:
print('开始测试异常情况')
r = 10 / self.num
print('result:', r)
except TypeError as e:
print('TypeError:', e)
except ZeroDivisionError as e:
print(e)
finally:
print('finish')
op_test1 = Test(num=2)
op_test1.unnormal()
op_test2 = Test(num='test')
op_test2.unnormal()
op_test3 = Test(num=0)
op_test3.unnormal()
示例运行结果: