开发者

try...else...except syntax error

I can't understand this...

Cannot get this code to run and I've no idea why it is a syntax error.


    try:
        newT.read()
        #existingArtist = newT['Exif.I开发者_如何学JAVAmage.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

Syntax error occurs on the last "except:". Again...I have no idea why python is throwing a syntax error (spent ~3hrs on this problem).


You can't have another except after the else. The try, except, and else blocks aren't like function calls or other code - you can't just mix and match them as you like. It's always a specific sequence:

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)

If you want to catch an error that occurs during the else block, you'll need another try statement. Like so:

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

FYI, the same applies if you want to catch an error that occurs during the except block - in that case as well, you would need another try statement, like this:

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


Reading the documentation would give you this phrase:

The try ... except statement has an optional else clause, which, when present, must follow all except clauses.

Move else to the end of your handler.


looking at the python documentation: http://docs.python.org/reference/compound_stmts.html#the-try-statement It doesn't look like you can have multiple elses with try. Maybe you meant finally at the end?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜