如果遇到任何异常,我想运行一行代码,但如果try成功,则不想运行,这有点像使用try/except时的else
相反。你知道吗
目前,如果发生异常,我将exceptionOccured
设置为True,但我猜应该有一种更为python的方法来实现这一点。你知道吗
这是我目前的代码,它试图从一个列表中编辑字典中的值,如果它们不存在,则创建键。如何重做异常以使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]
只需在一个处理程序中捕获两个异常:
如果异常处理程序更复杂,还可以使用以下函数:
我可能会同意Martijn的回答,但是您也可以将try/except块包装在另一层try/except中(在实际代码中,我不赞成这样使用bare except,或者更可能定义一个新的异常,它是从您想要检测的任何
except:
子句中抛出的)相关问题 更多 >
编程相关推荐