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

转载于:https://www.cnblogs.com/yxwxy/p/10444310.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值