简体   繁体   中英

Can I not use multiple Exceptions?

When I try to use multiple exceptions, for some reason I get the error:

SyntaxError: default 'except:' must be last

Code:

try:
    to_address = item["tx"]
    amount_xrp = int(item["tx"]["TakerGets"])/1000000.0
except:
    to_address = item["tx"]
except:
    to_address = "Cancellation"#item["tx"]["TakerPays"]
    amount_xrp = "NA"

The except: clause catches any exception. There's no sense in using it twice. What would it mean?

Your example is not correct Python syntax. You could do the following:

try:
    to_address = item["tx"]
    amount_xrp = int(item["tx"]["TakerGets"])/1000000.0

except:
    try:
        to_address = item["tx"]

    except:
        to_address = "Cancellation"#item["tx"]["TakerPays"]
        amount_xrp = "NA"

My best guess at what you're trying to achieve here is to have to_address be set to Cancellation if it's not in items , and have amount_xrp be set to 'NA' if to_address doesn't have a 'TakerGets' key.

to_address = item.get('tx', 'Cancellation') #returns 'Cancellation' if no key 'tx'
amount_xrp = 'NA'

if to_address != 'Cancellation':
    try:
        amount_xrp = int(to_address["TakerGets"])/1000000.0
    except KeyError:
        pass

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM