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

python中的异常未生成预期结果,python,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'

我试图在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.

我也对所有的错误感到例外。如果我不熟悉命令产生的错误,如何找到常见错误以查找?所以我可以把它们放在例外情况中。

在第二行,您使用
添加变量,而在第三行,您使用
添加变量

可能
收件人地址
未定义

由于您排除了错误,因此无法跟踪它

考虑捕获
异常
并将其分配给变量,如
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.")
您还需要将
更改为\u address
更改为
更改为\u addr
,这样except块就不会执行:

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.")

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

class MyE(Exception):
    pass

try:
    raise MyE()
except Exception as e:
    print(type(e))
这将产生:

捕获异常的原因是由于未定义的变量(
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
,但都失败了。

停止使用覆盖的
except
,您将看到一条很好的异常消息,告诉您实际出了什么问题。可能
收件人地址不存在。(前面的那行使用
添加地址,而不是
地址)我确实收到了电子邮件。因此,to_地址存在。我应该显示更多我的代码吗?@bluethundr我想他指的是发送邮件后第一次打印时使用的
to_address
变量。我们认为发生的情况是,邮件被发送,然后在第一次打印时计算
to_address
时抛出
未定义的
异常。我已更新代码以显示整个函数。。Grazi.@bluethundr不,它不是,您只在print语句中使用它,实际的
to_address
to_addr
,您在print语句之前使用了一行谢谢。就这样!