NineTail
NineTail

Reputation: 223

Exception Handling for function arguments

I'm starting to work with Python again and have an issue with how to handle exceptions from arguments in a function. Say someone does not enter a toaddr or a fromaddr or subject or body. Or they enter a fromaddr but not a toaddr. How can I tell if they are putting in a to or from? Say I do:

SendMail('', [email protected], Message, message body)

This works becuase I'm providing all the arugments, but if I leave toaddr blank I get not enough requirements error.

I don't think I'm explaining this very well :(.

My function is this:

def SendMail(toaddr, fromaddr, subject, body, attach=False):
    # create a MIME(Multipurpose Internet Mail Extension)
    msg = MIMEMultipart()

    # assign toaddr, fromaddr and subject to lists
    msg['To'] = toaddr
    msg['From'] = fromaddr
    msg['Subject'] = subject

    msg.attach(MIMEText(body, 'plain'))

    # attach a file if set to true
    if attach == True:
        filename = raw_input('fullpath/filename.extension>>> ')
        attachment = open(filename, "rb")

        part = MIMEBase('application', 'octet-stream')
        part.set_payload((attachment).read())
        encoders.encode_base64(part)
        part.add_header('Content-Disposition', "attachment; filename= %s" % filename)

        msg.attach(part)

    # establish connection to smtp server and send mail
    try:
        print('Sending Mail')
        server = smtplib.SMTP('mail.server.com', 25)
        text = msg.as_string()
        server.sendmail(fromaddr, toaddr, text)
        server.quit()
        print('Mail Sent!')
    except smtplib.SMTPException:
        print("Could not send mail")
        pass
    except smtplib.socket.error:
        print("Could not connect to server")
        pass

Upvotes: 2

Views: 1767

Answers (1)

kdopen
kdopen

Reputation: 8215

You have two choices

  • Validate your arguments in your SendMail function and raise a suitable exception (e.g. ValueError)
  • Pass the invalid arguments to the server.sendmail function, let it raise the exception, and don't catch it.

Either way, there's nothing you can sensibly do to deal with the exception, so simply let it propagate to the caller.

Consider a toy example

def divide(a, b):
  return a / b;

Now this can be broken in a number of ways:

  • Passing in a value of zero for B
  • Passing in a string for a or b
  • Passing in any other type for which the divide operator is not defined.

So you could check for all those things (assume this only works for int)

def divide(a,b):
  if not (isinstance(a,int) and isinstance(b,int)):
    raise ValueError("Arguments must both be integers")

  if b == 0:
    raise ValueError("Attempt to divide by zero")

  return a / b

Or you can just leave it as is, and let Python raise the appropriate exception

Upvotes: 3

Related Questions