python中的异常未产生预期的结果

时间:2019-04-22 21:39:49

标签: python

我正在尝试在python中创建异常:

to_addr = input("Enter the recipient's email address: ")
print("To address:", to_addr)
from_addr = 'cloudops@noreply.company.com'
subject = 'Welcome to AWS'
content = mail_body
msg = MIMEMultipart()
msg['From'] = from_addr
msg['To'] = to_addr
msg['Subject'] = subject
body = MIMEText(content, 'html')
msg.attach(body)
server = smtplib.SMTP('smtpout.us.companyworld.company.com', 25)
try:
    server.send_message(msg, from_addr=from_addr, to_addrs=[to_addr])
    print("Email was sent to: %s", to_address)
except:
    print("Email was not sent.")

发生的事情是server.send_message函数正常工作。它发送了电子邮件,我收到了。

但是异常会打印其语句。

这是我的输出:

Enter the recipient's email address: tdunphy@company.com
To address: tdunphy@company.com
Email was not sent.

我也排除所有错误。如果我不熟悉命令产生的错误,如何查找常见错误?这样我就可以把它们放在例外中。

2 个答案:

答案 0 :(得分:3)

第二行使用to_addr变量,第三行使用to_address变量

可能to_address未定义

由于您除了错误以外,您无法跟踪它

考虑捕获Exception并将其分配给变量e

try:
    server.send_message(msg, from_addr=from_addr, to_addrs=[to_addr])
    print("Email was sent to: %s", to_address)
except Exception as e:
    print(repr(e)) # it can be a logging function as well
    print("Email was not sent.")

此外,您需要像这样将to_address更改为to_addr,以便else块不会执行:

try:
    server.send_message(msg, from_addr=from_addr, to_addrs=[to_addr])
    print("Email was sent to: %s", to_addr)
except Exception as e:
    print(repr(e)) # it can be a logging function as well
    print("Email was not sent.")

答案 1 :(得分:0)

您可以简单地让它传播,然后在控制台中检查您遇到的特定错误类别,或者可以执行以下操作:

class MyE(Exception):
    pass

try:
    raise MyE()
except Exception as e:
    print(type(e))

将会产生:<class '__main__.MyE'>

捕获到您的异常的原因是由于未定义的变量(to_address)。

考虑以下示例:

try:
    print("yes")
    print(some_undefined_variable)
except Exception as e:
    print("no", e)

这将产生:

yes
no name 'some_undefined_variable' is not defined

这意味着在评估不存在的变量时,两个try/except均被调用并且失败。