try...else...except语法错误

3 投票
3 回答
24386 浏览
提问于 2025-04-15 22:29

我看不懂这个...

我无法让这段代码运行,完全不知道为什么会出现语法错误。


    try:
        newT.read()
        #existingArtist = newT['Exif.Image.Artist'].value
        #existingKeywords = newT['Xmp.dc.subject'].value

    except KeyError:
        print "KeyError"

    else:
        #Program will NOT remove existing values
        newT.read()
        if existingArtist != "" :
            newT['Exif.Image.Artist'] = artistString


        print existingKeywords

        keywords = os.path.normpath(relativePath).split(os.sep)
        print keywords
        newT['Xmp.dc.subject'] = existingKeywords + keywords

        newT.write()
    except:
        print "Cannot write tags to ",filePath

语法错误出现在最后一个“except:”上。再次强调...我真不知道为什么Python会报语法错误(我花了大约3个小时在这个问题上)。

3 个回答

0

在查看Python的文档时,发现关于try语句的部分:http://docs.python.org/reference/compound_stmts.html#the-try-statement。看起来在try语句中不能有多个else。也许你是想在最后加一个finally呢?

3

阅读文档时,你会看到这样一句话:

try ... except 语句有一个可选的 else 部分,如果有的话,它必须放在所有 except 部分之后。

把 else 移到你的处理程序的最后面。

25

else 后面不能再有另一个 excepttryexceptelse 这些块的使用顺序是固定的,不能随意组合,就像是有特定的规则一样。

try:
    # execute some code
except:
    # if that code raises an error, go here
    # (this part is just regular code)
else:
    # if the "try" code did not raise an error, go here
    # (this part is also just regular code)

如果你想捕捉在 else 块中发生的错误,你需要再写一个 try 语句。可以这样做:

try:
    ...
except:
    ...
else:
    try:
        ...
    except:
        ...

顺便说一下,如果你想捕捉在 except 块中发生的错误,情况也是一样的,这时你同样需要再写一个 try 语句,像这样:

try:
    ...
except:
    try:
        ...
    except:
        ...
else:
    ...

撰写回答