python: exception inside try doesn't jump to except

Question:

I am trying to search within the EU parliment votes’ description.
They are standard xml files. So far I noticed 2 versions of the votes’ result: where the description is text and where it is an url.
Fails at this file: https://www.europarl.europa.eu/doceo/document/PV-9-2022-09-12-RCV_FR.xml
Works fine on the following file: https://www.europarl.europa.eu/doceo/document/PV-9-2022-07-06-RCV_FR.xml

My problem is not the failure itself (that’s why I added the try clause) but that code execution doesn’t jump to the except path, just exits here with this: string indices must be integers

Please help, why isn’t the error properly handled?

for currentfile in f:
    mytree = ET.parse(xmlfiles + "\" + currentfile)
    myroot = mytree.getroot()
    dixml = etree_to_dict(myroot)
    for votes in dixml['PV.RollCallVoteResults']['RollCallVote.Result']:
        try:
            title = votes['RollCallVote.Description.Text']  #fails here
            titletype = type(title)
            if titletype == dict:
                title=title['#text']
        except :
            title = votes['RollCallVote.Description.Text']['a']['#text']
        try:
            ltitle = title.lower()
        except :
            print(type(title))
        if stringtosearch in ltitle:
            print(title,currentfile)

edit:
full trace:

  Message=string indices must be integers
  Source=...debug.py
  StackTrace:
  File "...debug.py", line 44, in <module>
    title = votes['RollCallVote.Description.Text'] 

During handling of the above exception, another exception occurred:

  File "...debug.py", line 44, in <module>
    title = votes['RollCallVote.Description.Text']
  File "...debug.py", line 49, in <module> (Current frame)
    title = votes['RollCallVote.Description.Text']['a']['#text']
Asked By: vilmarci

||

Answers:

This would happen if there is a new exception raised within your catch block, I would presume specifically the votes object at some point of you accessing it, raises this exception.

Try printing out votes and then each time you access it by indexing print it out you’ll see to which extent you can continue accessing it via string index ( votes[‘string’] ).

Answered By: LeTorky
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.