1、普通异常捕捉
# coding=UTF8
def getNum(n):
try:
return 10/n
except IOError: # 捕获异常
print('Error: IOError argument.')
except ZeroDivisionError:
print('Error: ZeroDivisionError argument.')
else: # 在没有出现异常时执行
print('else -->')
finally: # 无论是否出现异常都会执行
print('finally -->')
getNum(0)
print('----------------------------------------')
getNum(1)
输出结果:
2、自定义异常
# coding=UTF8
# 自定义异常类
class MyExc(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
if self.value == 0:
return '被除数不能为0'
def getNum(n):
try:
if n == 0:
exc = MyExc(n)
print(exc)
else:
print(10 / n)
except:
pass
getNum(1)
print('---------------------------------')
getNum(0)
输出结果: