Python只在exception为m时运行某些东西

2024-09-27 19:23:05 发布

您现在位置:Python中文网/ 问答频道 /正文

如果遇到任何异常,我想运行一行代码,但如果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]

Tags: falsetrueiftypedictraiseprinttry
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()

我可能会同意Martijn的回答,但是您也可以将try/except块包装在另一层try/except中(在实际代码中,我不赞成这样使用bare 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.

相关问题 更多 >

    热门问题