I have a script that needs to use a slightly unusual try structure, of the general form:
try:
# Try to get object 1 (may or may not exist)
except:
# Try to get object 2 (may or may not exist)
else:
try:
# Try to append object 2 (which may not exist) to object 1, which has been retrieved already
# Do stuff with the retrieved object/composite object
I always get an 'unexpected indent' error at the last section (where I try to do stuff with my retrieved object), unless I put a dummy finally block in:
try:
# Try to get object 1 (may or may not exist)
except:
# Try to get object 2 (may or may not exist)
else:
try:
# Try to append object 2 (which may not exist) to object 1, which has been retrieved already
finally:
dummy = 1
# Do stuff with the retrieved object/composite object
There is zero point to setting dummy = 1, other than that it seems to work. Is this expected behaviour? Is it possible to use such a nest (or alternative syntax) without resorting to dummy lines of code!?
Finally, in one place where I do this, there is an additional line of code that is only required if the second 'try' statement executes without exception, but there seems to be no way of making this work elegantly with an 'else' clause on the inner/second 'try'. The following gives an 'invalid syntax' error on the second 'else' line:
try:
# Try to get object 1 (may or may not exist)
except:
# Try to get object 2 (may or may not exist)
else:
try:
# Try to append object 2 (which may not exist) to object 1, which has been retrieved already
else:
# Do action only required on composite object
finally:
dummy = 1
# Do stuff with the retrieved object/composite object