# coding: utf-8
import sys
print("Python版本信息: ", sys.version)
class BubbleExceptions(object):
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_val:
print('Bubble up exception: %s.' % exc_val)
pass
return False
pass
with BubbleExceptions():
print(5 + 5)
with BubbleExceptions():
print(5 / 0)
输出
Python版本信息: 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit (AMD64)]
10
Bubble up exception: division by zero.
Traceback (most recent call last):
File "D:/workspace/Pycharm/PurePythonProject/Test.py", line 23, in <module>
print(5 / 0)
ZeroDivisionError: division by zero
终止异常
代码
# coding: utf-8
import sys
print("Python版本信息: ", sys.version)
class BubbleExceptions(object):
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_val:
print('Suppressing exception: %s.' % exc_val)
pass
return True
pass
with BubbleExceptions():
print(5 + 5)
with BubbleExceptions():
print(5 / 0)
输出
Python版本信息: 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit (AMD64)]
10
Suppressing exception: division by zero.
注意
没有返回表达式5 / 0的值, 异常在计算该值的过程中引发, 从而触发__exit__的运行.
处理特定异常
代码
# coding: utf-8
import sys
print("Python版本信息: ", sys.version)
class HandleValueError(object):
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if not exc_type:
return True
if issubclass(exc_type, ValueError):
print('Handling ValueError: %s.' % exc_val)
pass
return False
pass
with HandleValueError():
raise ValueError('Value Error')
with HandleValueError():
raise TypeError('Type Error')
输出
Python版本信息: 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit (AMD64)]
Handling ValueError: Value Error.
Traceback (most recent call last):
File "D:/workspace/Pycharm/PurePythonProject/Test.py", line 23, in <module>
raise ValueError('Value Error')
ValueError: Value Error