Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 233527
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T20:06:36+00:00 2026-05-11T20:06:36+00:00

I have searched for other posts, as I felt this is a rather common

  • 0

I have searched for other posts, as I felt this is a rather common problem, but all other Python exception questions I have found didn’t reflect my problem.

I will try to be as specific here as I can, so I will give a direct example. And pleeeeease do not post any workarounds for this specific problem. I am not specifically interested how you can send an email much nicer with xyz.
I want to know how you generally deal with dependent, error prone statements.

My question is, how to handle exceptions nicely, ones that depend on one another, meaning:
Only if the first step was successful, try the next, and so on. One more criterion is: All exceptions have to be caught, this code has to be robust.

For your consideration, an example:

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

This looks extremely unpythonic to me, and the error handling code is triple the real business code, but on the other hand how can I handle several statements that are dependent on one another, meaning statement1 is prerequisite for statement2 and so on?

I am also interested in proper resource cleanup, even Python can manage that for itself.

Thanks, Tom

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-11T20:06:36+00:00Added an answer on May 11, 2026 at 8:06 pm

    Instead of using the try/except’s else block, you could simply return when it errors:

    def send_message(addr, to, msg):
        ## Connect to host
        try:
            server = smtplib.SMTP(host) #can throw an exception
        except smtplib.socket.gaierror:
            return False
    
        ## Login
        try:
            server.login(username, password)
        except SMTPAuthenticationError:
            server.quit()
            return False
    
        ## Send message
        try:
            server.sendmail(addr, [to], msg.as_string())
            return True
        except Exception: # try to avoid catching Exception unless you have too
            return False
        finally:
            server.quit()
    

    That’s perfectly readable and Pythonic..

    Another way of doing this is, rather than worry about the specific implementation, decide how you want your code to look, for example..

    sender = MyMailer("username", "password") # the except SocketError/AuthError could go here
    try:
        sender.message("addr..", ["to.."], "message...")
    except SocketError:
        print "Couldn't connect to server"
    except AuthError:
        print "Invalid username and/or password!"
    else:
        print "Message sent!"
    

    Then write the code for the message() method, catching any errors you expect, and raising your own custom one, and handle that where it’s relevant. Your class may look something like..

    class ConnectionError(Exception): pass
    class AuthError(Exception): pass
    class SendError(Exception): pass
    
    class MyMailer:
        def __init__(self, host, username, password):
            self.host = host
            self.username = username
            self.password = password
    
        def connect(self):
            try:
                self.server = smtp.SMTP(self.host)
            except smtplib.socket.gaierror:
                raise ConnectionError("Error connecting to %s" % (self.host))
    
        def auth(self):
            try:
                self.server.login(self.username, self.password)
            except SMTPAuthenticationError:
                raise AuthError("Invalid username (%s) and/or password" % (self.username))
    
        def message(self, addr, to, msg):
            try:
                server.sendmail(addr, [to], msg.as_string())
            except smtplib.something.senderror, errormsg:
                raise SendError("Couldn't send message: %s" % (errormsg))
            except smtp.socket.timeout:
                raise ConnectionError("Socket error while sending message")
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a problem adding strings to a TStringList. I've searched other posts but
I've have searched on this and it seems to be a catch all, unfortunately
I've searched for this a little but I have not gotten a particularly straight
I have searched google but it seems no one has come across this issue.
I have searched Google and Stackoverflow for this question, but I still don't understand
I have searched around, and it seems that this is a limitation in MS
I have searched but apparently my google foo is weak. What I need is
Wouldn't this be overkill and only one of these necessary? I've searched and found
How can I find the parameters of an undocumented Dll function? I have searched
I have a form that searches all rows in a single table (TServices) that

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.