异常 巩固3

Posted hany-postq473111315

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了异常 巩固3相关的知识,希望对你有一定的参考价值。

1.with open("文件路径","模式") as fp:
    操作
进入时 调用 __enter__ 方法
    def __enter__(self):
        print("开始执行 with 方法")
退出时 调用 __exit__ 方法
    def __exit__(self,type,value,traceback):
        print("退出 with 方法")
2.文件操作方法:
    打开、读取、关闭
    d = open(a,r)
    d.read()
    d.close()
3.可以自己定义异常,继承 Exception 类


程序:
# 查看 with 执行的方法
class sth(object):

    def __enter__(self):
        print("开始执行 with 方法")

    def __exit__(self,type,value,traceback):
        print("退出 with 方法")

with sth( ) as fp:
    # with 自动关闭文件
    pass


# 自定义异常
class myException(Exception):
    # 继承 Exception
    def __init__(self,error,msg):
        self.args = (error,msg)
        self.error = error
        self.msg = msg
try:
    raise myException(1,my exception)
except Exception as e :
    print(str(e))
    # (1, ‘my exception‘)

2020-04-12

以上是关于异常 巩固3的主要内容,如果未能解决你的问题,请参考以下文章

在tablayout片段之间进行通信[重复]

异常 巩固1

使用实体框架迁移时 SQL Server 连接抛出异常 - 添加代码片段

异常和TCP通讯

vscode代码片段建议bug

片段中的Android致命异常