How to catch AttributeError?

Question:

How can I catch AttributeError from this line and print message to the user, let’s say "you can’t change class="post" "

post_start = re.search('<div class="post">', html)

I tried with try, except AttributeError, raise, print but it’s always returning nothing.
That’s what I did:

try:
    post_start = re.search('<div class="post">', html)
except AttributeError:
    raise
else:
    print 'you can't change <div class="post">'
Asked By: SpringField

||

Answers:

re.search() returns None if no position in the string matches the pattern. Check for None and raise an exception:

post_start = re.search('<div class="post">', html)
if post_start is None:
    raise AttributeError('you can't change <div class="post">')
Answered By: alecxe
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.