只有在满足异常时,Python才会运行

时间:2015-03-10 15:07:25

标签: python

如果遇到任何异常,我想运行一行代码,但是如果尝试成功则不行,当使用try / except时,有点像else的反面。

目前,如果发生异常,我将exceptionOccured设置为True,但我猜测应该采用更加pythonic的方式。

这是我当前的代码,它是尝试从列表中编辑字典中的值,如果它们不存在则创建密钥。我如何重做异常以便不需要exceptionOccured

dictionaryValue = {"data": dict.fromkeys( [0, 1, 2, 3] ), "data2": {0: "test",1:"test2"}}

reducedDictionary = dictionaryValue
valueList = ["data", 1, 64, "Testing", "value"]
canOverwriteKeys = True
for i in valueList[:-2]:
    exceptionOccured = False
    try:
        if type( reducedDictionary ) != dict:
            raise ValueError()
        elif reducedDictionary.get( i, False ) == False:
            raise KeyError()
    except ValueError:
        print "not dictionary"
        reducedDictionary = {}
        exceptionOccured = True
    except KeyError:
        print "key doesn't exist"
        exceptionOccured = True
    if exceptionOccured or ( type( reducedDictionary[i] ) != dict and canOverwriteKeys ):
        print "setting key value"
        reducedDictionary[i] = {}
    reducedDictionary = reducedDictionary[i]
reducedDictionary[valueList[-2]] = valueList[-1]
print dictionaryValue

编辑:根据答案改进代码,谢谢:)

def editDictionary( dictionaryName, listOfValues, canOverwriteKeys=True ):
    reducedDictionary = dictionaryName
    for i in valueList[:-2]:
        if type( reducedDictionary ) != dict:
            reducedDictionary = {}
        try:
            if reducedDictionary.get( i, False ) == False:
                raise ValueError()
            elif type( reducedDictionary[i] ) != dict:
                if not canOverwriteKeys:
                    return
                raise KeyError()
        except( ValueError, KeyError ):
            reducedDictionary[i] = {}
        except:
            print "Something went wrong"
            return
        reducedDictionary = reducedDictionary[i]
    reducedDictionary[valueList[-2]] = valueList[-1]

2 个答案:

答案 0 :(得分:2)

只需在一个处理程序中捕获两个异常:

try:
    # ...
except (ValueError, KeyError) as e:
    if isinstance(e, ValueError):
        print "not dictionary"
        reducedDictionary = {}
    else:
        print "key doesn't exist"
    print "setting key value"
    reducedDictionary[i] = {}

如果您的异常处理程序更复杂,您还可以使用函数:

def handle_common_things():
    # things common to all exception handlers

try:
    # ...
except Exception1:
    # do exception-specific things
    handle_common_things()
except Exception2:
    # do exception-specific things
    handle_common_things()

答案 1 :(得分:1)

我可能会选择Martijn的答案,但你也可以在另一层try / except中包装你的try / except块(在真实的代码中,我对使用裸露的东西不屑一顾除此之外,或者更可能定义一个从你想要检测的任何except:子句中引发的新异常

def exception_test(val):
   try:
      try:
         result = 1.0 / val
      except ZeroDivisionError:
         print "Divide by zero"
         raise
      else:
         print "1 / {0} = {1}".format(val, result)
   except:
      print "there was an exception thrown."


>>> exception_test(2.0)
1 / 2.0 = 0.5
>>> exception_test(0)
Divide by zero
there was an exception thrown.