python 异常处理
python中特殊的异常处理
通常Exception能捕捉所有异常,但这些异常必须为python内部自定义的异常(并且不包括BaseException);若程序中抛出自定义异常,或者BaseException则该异常不能被Exception捕捉;但可以被BaseException或者不带参数的except捕捉
class CustomException(BaseException):
pass
try:
raise CustomException('an error accured')
except Exception as e:
print(f"catch exception {e}")
# 运行结果
Traceback (most recent call last):
File "C:/Users/wyx/Desktop/test.py", line 108, in <module>
raise CustomException('an error accured')
CustomException: an error accured
class CustomException(BaseException):
pass
try:
raise CustomException('an error accured')
except BaseException as e:
print(f"catch exception '{e}'")
# 运行结果
catch exception 'an error accured'
with在异常发生时自动执行对象的__exit__方法
使用with进行上下文管理时,只要__enter__方法已经执行完成,无论执行过程中是否抛出异常,__exit__方法均会执行
class A:
def __enter__(self):
# raise BaseException('error in content')
print('Enter class A')
def __exit__(self,Type, value, traceback):
print('exit class A')
with A():
raise BaseException('error in content')
# 结果
Enter class A
exit class A
Traceback (most recent call last):
File "C:/Users/wyx/Desktop/test.py", line 98, in <module>
raise BaseException('error in content')
BaseException: error in content