开发者

Try / except syntax in Python with two of the same exceptions

I am checking emails against two lists -- a list of domains and a list of individual emails. How would I construct the following try statement --

Try: 'email i开发者_运维知识库n email_list'

Except DoesNotExist: 'domain in domain list' # if email not found

Except DoesNotExist: 'print error message'   # if both email and domain not found

What syntax do I need to use to construct this statement?


It sounds like you're looking for something like:

if email in email_list:
    # do something with email
elif domain in domain_list:
    # do something with domain
else:
    print "neither email nor domain found"

There is probably no need for exceptions in this case.


Why don't define two exceptions: DomainDoesNotExists, EmailDomainDoesNotExists ?

try: 
    'email in email_list'
except DomainDoesNotExists:
    ...
except EmailDomainDoesNotExists:
    ...

There is no way to do what you want with only one Exception type (e.g. DoesNotExists).

But you better listen to @Greg Hewgill, in this case you don't need exceptions


It is hard to know what you are trying to do. Your capitalizations are a problem. When you catch exceptions, proceed from the most specific to the general. The first handler block handles the exception and puts you out of the try-except progression.

try:
    yourEmailRoutine
except DomainDoesNotExist:
    ##code to be carried out if domain does not exist...
    print "The domain %s does not exist." % yourDomainName

Since emails are often malformed, you might want to use Greg's suggestion to deal with this in an if-elif-else progression.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜