2

I'm trying to write a subscription list module. So, I have a statement that may, depending on the email id of the user, throw an index out of range error. If it does, I want the program to do something and if it doesn't I want the program to something else entirely. How would I go about this? Currently I have code that tries to add all user irrespective and crashes the program. What I would ideally like to have is something like this:

try:
    check_for_email_id.from_database
except IndexError:
    create.user_id.in_database
    user.add.to.subscribe_list

else:
    user.add.to.subscribe_list

I need to be able to add a block here saying, if there was no IndexError, omit the "do something" part and do the else part. Does Python provide an inbuilt option for this? Can I use if-else blocks in Try-Except statements?

And also, what would be a good approach to avoid writing the code for user.add.to.subscribe_list twice; other than creating a new user_add function?

1 Answers1

1

Yes, the else in a python try/except(else/finally) statement is for precisely that: something that you want to happen only if there are no exceptions:

import random
try:
    1 / random.randrange(2)
except Exception as e:
    print(e)
else:
    print('we succeeded!')
finally:
    # always prints
    print('we just tried to do some division!')

In answer to your second question, it looks like what you really want is to use the finally clause:

try:
    check_for_email_id.from_database
except IndexError:
    create.user_id.in_database
finally:
    # this gets called if there was an error or not
    user.add.to.subscribe_list
rofls
  • 4,993
  • 3
  • 27
  • 37
  • 1
    So, for avoiding code redundancy, should that be a different question or can I expect answers here? And thank you for your answer. That helped. –  Feb 09 '17 at 02:55
  • @Di437 if you put that in the `finally` clause, with no `else` it will be called if there was an error or not. I'll add an edit to show what I mean. – rofls Feb 09 '17 at 03:29