• 自动处理错误?
    1. # 不用写 try
    2. with open('name.txt') as f:
    3. for i in f:
    4. print(i)
    • 类似装饰器
    1. class TestWith:
    2. def __enter__(self):
    3. print('enter')
    4. def __exit__(self, exc_type, exc_val, exc_tb):
    5. print('exit')
    6. with TestWith():
    7. print('Test is running')
    8. # 输出
    9. enter
    10. Test is running
    11. exit
    • 捕获类的异常
    1. class TestWith:
    2. def __enter__(self):
    3. print('enter')
    4. def __exit__(self, exc_type, exc_val, exc_tb):
    5. if exc_tb is None:
    6. print('normal exit')
    7. else:
    8. print('err: %s' % exc_tb)
    9. # 可以想像成 with 包裹了 TestWith 对象,
    10. # 如果在运行中产生异常, 那么异常会传递给对象.
    11. with TestWith():
    12. print('Test is running')
    13. # 手动抛出异常
    14. raise NameError('testNameError')
    15. # 输出
    16. enter
    17. Test is running
    18. err: <traceback object at 0x7fe36e8614c0>
    19. Traceback (most recent call last):
    20. File "/home/jdxj/workspace/study-python/with.py", line 15, in <module>
    21. raise NameError('testNameError')
    22. NameError: testNameError