Try ... else ... except for syntax error
I do not understand this...
This code cannot be run and I don't know why it is a syntax error.
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
A syntax error occurs with the last "except:". Again ... I have no idea why python is throwing a syntax error (spent ~ 3 hours on this issue).
a source to share
else
There can be no other after except
. Blocks try
, except
and are else
not like function calls or other code - you can't just mix and match them as you see fit. This is always a certain 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 a block else
, you need a different statement try
. For instance:
try:
...
except:
...
else:
try:
...
except:
...
FYI, same thing if you want to catch an error that occurs during a block except
- in which case, you need a different operator try
, like:
try:
...
except:
try:
...
except:
...
else:
...
a source to share
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 in the end you meant finally?
a source to share