简体   繁体   中英

Python 3 error handling running both try and except

I am trying to implement error handling in a Python 3 script by getting the SMTPlib library to send an email when it encounters an error like this..

if value.isdigit() :
    print ("Value is an integer")
else :
    try:
        server = smtplib.SMTP(email_server, email_port)
        server.ehlo()
        server.starttls()
        server.login(email_login, email_pass)
        server.sendmail("me@example.com", "me@example.com", message)
        server.close()
        sys.exit()
    except:
        print ("Error - Was unable to send email")
        sys.exit()

This works correctly if the value is an integer, but if it is not then the email gets correctly sent but the Error message is also printed to the screen.

Why is my script running the except section as well?

sys.exit is implemented by raising an exception. When sys.exit is called after server.close , that SystemExit exception is caught.

Here is a little proof:

import sys 

try:
  print("hello")
  sys.exit()
except:
  print("exception!")

The basic rules for exception handling were not obeyed. At least except Exception: should have been used. Better except Exception as err: with err logged or printed. And the best approach is to handle only exceptions originating from the SMTP transaction guarded by try/except .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM