异常捕获机制
异常信息与异常捕获
代码示例
- 异常嵌套:
try:
1/0
except Exception as e:
try:
1/0
except Exception as f:
pass
print (e)
division by zero
- 捕获异常后,不再向下执行:
def f1():
1/0
def f2():
list = []
list[1]
f1()
def f3():
f2()
try:
f3()
except (ZeroDivisionError,Exception) as e:
print (e)
list index out of range
- 自定义异常
# 自定义异常
class UserInputError(Exception):
def __init__(self,ErrorInfo):
super().__init__(self,ErrorInfo)
self.errorinfo = ErrorInfo
def __str__(self):
return self.errorinfo
userintput = 'a'
try:
if (not userintput.isdigit()):
raise UserInputError('用户输入错误')
except UserInputError as ue:
print (ue)
finally:
del userintput
用户输入错误
- pretty_errors
import pretty_errors
def foo():
1/0
foo()
- 重写Open
# with open('index.html','r',encoding='utf8') as f2:
# data = f2.read()
class Open:
def __enter__(self):
print ('open')
def __exit__(self, exc_type, exc_val, exc_tb):
print ('close')
# 把类伪装成函数
def __call__(self, *args, **kwargs):
pass
# 使用with时候,执行了__enter__()和__exit__()
with Open() as f:
pass
open
close