python异常捕获语法
try:
# 写你的代码 ...
pass;
except Exception as err:
# 报错了之后捕获,进行异常处理
print(err);
else:
# 程序没报错,进行其他处理
pass;
finally:
# 上面的全进行玩了之后进行其他处理
pass;
raise关键字,手动抛出异常
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;
with关键字 python的骚操作
'''
上下文开启 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自定义异常,自行百度;
gou领导一直催我前几天的开发任务完成没,写完了就告诉他没写完,一个劲催催催,gdx,每天划水学python,多美好;