我可以不使用多个例外吗?

时间:2018-10-22 23:51:01

标签: python

当我尝试使用多个异常时,由于某种原因,我得到了错误:

SyntaxError: default 'except:' must be last

代码:

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"

3 个答案:

答案 0 :(得分:0)

except:子句捕获任何异常。两次使用没有意义。是什么意思?

答案 1 :(得分:0)

您的示例不正确的Python语法。您可以执行以下操作:

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"

答案 2 :(得分:0)

对于您要达到的目标,我的最佳猜测是将to_address设置为Cancellation(如果不在items中),并设置amount_xrp如果to_address没有一个'TakerGets'键,则将其设置为“ NA”。

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