我在Stack Overflow上搜索了其他帖子,因为我认为这是一个相当常见的问题,但我发现所有其他Python异常问题都不反映我的问题。
我会尽可能具体地说明问题,所以我将给出一个直接的例子。并且请不要针对这个具体问题发布任何解决方法。我并不特别关心如何使用xyz更好地发送电子邮件。我想知道您通常如何处理依赖于彼此的容易出错的语句的异常。
我的问题是,如何优雅地处理异常,即仅在第一步成功后再尝试下一步,以此类推。另一个标准是:必须捕获所有异常,因此代码必须健壮。
以下是一个示例供您参考:
try:
server = smtplib.SMTP(host) #can throw an exception
except smtplib.socket.gaierror:
#actually it can throw a lot more, this is just an example
pass
else: #only if no exception was thrown we may continue
try:
server.login(username, password)
except SMTPAuthenticationError:
pass # do some stuff here
finally:
#we can only run this when the first try...except was successful
#else this throws an exception itself!
server.quit()
else:
try:
# this is already the 3rd nested try...except
# for such a simple procedure! horrible
server.sendmail(addr, [to], msg.as_string())
return True
except Exception:
return False
finally:
server.quit()
return False
我认为这段代码非常不符合Python的编程规范,而且错误处理代码比实际业务代码还要多三倍,但另一方面,如果有几个语句是彼此依赖的,也就是说statement1是statement2的前提条件等等,那么怎样处理呢?
我还对适当的资源清理很感兴趣,即使是Python自己也可以进行管理。
谢谢,汤姆