Roly Poly
Roly Poly

Reputation: 559

Shouldn't my try/except block have caught this AttributeError?

I am using Python 3.7 and I have a question about some code & an error that just happened.

Basically my code reads like this:

try:
    # Sometimes the <span> tag has a <a> tag as a child element...
    post_company = card.find("span", {"class": "company"}).find("a").decode_contents().replace("\u2026", "...")
except AttributeError:
    # ...And sometimes it doesn't.
    post_company = card.find("span", {"class": "company"}).decode_contents().replace("\u2026", "...")

But I still got this error message:

Traceback (most recent call last):
  File "C:/Users/Roland/dir1/2020/Indeed-Scraper/database/database.py", line 163, in update_post_from_soup
    post_company = card.find("span", {"class": "company"}).find("a").decode_contents().replace("\u2026", "...")
AttributeError: 'NoneType' object has no attribute 'find'

Line 163 mentioned in the trace is the line in the try block. So it raised an AttributeError because there was no <a></a> tag within the <span>. I get that. But why didn't my except block catch this and execute the alternative line? Isn't except AttributeError handling precisely that error msg?

As this link says: "The except clause will only catch exceptions that are raised inside of their corresponding try block". So yeah, it should've caught it, no?

Upvotes: 0

Views: 388

Answers (1)

Hrisimir Dakov
Hrisimir Dakov

Reputation: 587

It actually catches it, but your 'except' block generates anoter one.

Upvotes: 3

Related Questions