zoukankan      html  css  js  c++  java
  • 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
    
  • 相关阅读:
    新家开始了
    FreeMarker过时的方法 new Configuration()
    基于Spring封装的Javamail实现邮件发送
    Spring中PropertiesLoaderUtils应用
    SpringBoot基于数据库的定时任务统一管理
    ActiveMQ点对点模式
    springboot整合swagger2
    dubbo简单示例
    SpringCLoud之搭建Zuul网关集群
    微服务项目框架搭建
  • 原文地址:https://www.cnblogs.com/yxwxy/p/10444310.html
Copyright © 2011-2022 走看看