如何在python

时间:2017-04-24 10:45:19

标签: python exception exception-handling try-catch

我可以在try - catch上看到几个主题,但似乎没有讨论错误,如果有任何来自finally块本身。我发现如果它在finally块中,则不会处理错误。什么是最终管理的理想方式?

例如。下面是邮件功能。如果try块中有任何错误,最后将执行本身未启动的quit方法,因此会发生未处理的错误。那么最好确保finally块中没有错误发生吗?

def send_email(ldap, email_address, password, msg):
    try:
        message = MIMEMultipart('alternative')
        message['To'] = email.utils.formataddr(('Recipient', '%s@abc.com'%email_address))
        message['From'] = email.utils.formataddr(('Author', '%s@abc.com'%email_address))
        message['Subject'] = 'Sample subject'
        text = "%s"%msg
        html = MIMEText('<html><head></head><h2>data</h2><body><p>%s</p></body></html>'%msg,'html')

        message.attach(html)
        server = smtplib.SMTP(host="ip",port=0)
        server.set_debuglevel(True)

        # identify ourselves, prompting server for supported features
        server.ehlo()

        if server.has_extn('STARTTLS'):
            server.starttls()
            server.ehlo() 

        server.login(ldap, password)
        print "%s@abc.com, %s@abc.com, %s "%(email_address,email_address,message.as_string())
        server.sendmail('%s@abc.com'%email_address, "%s@abc.com"%email_address, message.as_string())
    finally:
        server.quit()

2 个答案:

答案 0 :(得分:1)

不要将一堆代码(做不同的事情)放到一个try / except块中,但是你可以在finally块中轻松添加if / else条件:

def send_email(ldap, email_address, password, msg):
    server = None  #make sure server variable is always defined.
    try:
        ...
        server = smtplib.SMTP(...)
        ...
    finally:
        if server and isinstance(x, smtplib.SMTP):
            server.quit()

答案 1 :(得分:1)

由于您的console.debug( variable )块仅用于确保服务器连接正确关闭,显而易见的答案是仅将相关部分包装在finally块中:

try

更好的解决方案是将此代码拆分为不同的函数,每个函数都具有明确定义的责任 - 准备消息,获取与服务器的连接等,即:

def send_email(ldap, email_address, password, msg):
    message = MIMEMultipart('alternative')
    message['To'] = email.utils.formataddr(('Recipient', '%s@abc.com'%email_address))
    message['From'] = email.utils.formataddr(('Author', '%s@abc.com'%email_address))
    message['Subject'] = 'Sample subject'
    text = "%s"%msg
    html = MIMEText('<html><head></head><h2>data</h2><body><p>%s</p></body></html>'%msg,'html')

    message.attach(html)
    server = smtplib.SMTP(host="ip",port=0)

    # now you can start the try block:
    try:
        server.set_debuglevel(True)    
        # identify ourselves, prompting server for supported features
        server.ehlo()
        if server.has_extn('STARTTLS'):
            server.starttls()
            server.ehlo() 
        server.login(ldap, password)
        print "%s@abc.com, %s@abc.com, %s "%(email_address,email_address,message.as_string())
        server.sendmail('%s@abc.com'%email_address, "%s@abc.com"%email_address, message.as_string())
    finally:
        server.quit()