I have a script for controlling some instruments during an experiment that looks like this:
camera = Camera()
stage = Stage()
results = []
# loads of other initialization
for n in steps:
stage.move(n)
img = camera.capture()
# loads of other function/method calls
results.append(img)
results = np.array(results)
np.savetxt('data.txt',results)
camera.close()
stage.close()
If an Exception occurs inside the loop (e.g. some hardware problem for the camera or the stage), then I want to go save the results
and close the instruments. If an Exception occurs before the loop, then I just want to close the instruments. How to do this? I can put many try/except
statements, but are there other better methods?