Pythonの例外キャプチャとキーワード

Python例外キャプチャ構文

try:
    # 写你的代码 ...
    pass;
except Exception as err:
    # 报错了之后捕获,进行异常处理
    print(err);
else:
    # 程序没报错,进行其他处理
    pass;
finally:
    # 上面的全进行玩了之后进行其他处理
    pass;

キーワードを上げ、手動で例外をスローします

try:
    # 手动抛出异常
    raise Exception("奥利给");
except Exception as err:
    # 报错了之后捕获,进行异常处理
    print(err);
else:
    # 程序没报错,进行其他处理
    pass;
finally:
    # 上面的全进行玩了之后进行其他处理
    pass;
try:
    # 手动抛出异常
    raise Exception("奥利给");
except Exception as err:
    # 报错了之后捕获,进行异常处理
    print(err);
    # 将异常继续抛出 如果不想追加到系统变量__cause__中,吧下面的err改为None即可
    raise Exception from err;
else:
    # 程序没报错,进行其他处理
    pass;
finally:
    # 上面的全进行玩了之后进行其他处理
    pass;

キーワードpythonでのSao操作

'''
上下文开启   def __enter__(self)
上下文关闭   def __exit__(self,exc_type,exc_val,exc_tb)
'''
class Message:

    class _Connect:
        def build(self):
            print("Connect 建立消息发送通道");
            return True;
        def close(self):
            print("Connect 关闭消息发送通道");

    def __enter__(self):
        print("with 语句开始执行");
        self.__conn = Message._Connect();
        if not self.__conn.build():
            print("建立通道失败");
        return self;

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("with 语句执行完毕");
        self.__conn.close();

    def send(self,msg):
        print("发送的消息为:{}".format(msg));

def main():
    with Message() as message:
        message.send("1");
        message.send("2");
        message.send("3");

if __name__ == '__main__':
    main();

Pythonカスタム例外、Baidu自体。

gouのリーダーは、数日前に開発タスクを完了するように私に促してきました。私が書き終えた後、私は彼に書き終えていないことを伝えました。

おすすめ

転載: blog.csdn.net/weixin_44887276/article/details/114583733