Should the exception blocks in a try-except
sequence be specific only to those exceptions which may originate from the try
? Or can they be inclusive of exceptions that may arise from handling the original exception caught?
I currently have a function that has a try-except block to write some data to file. When a specific sizing exception is met (meaning the file is at max size), the write fails (as it should), the exception is caught and a new file is attempted to be create; if successful, the write attempt occurs again otherwise and exception is caught for failure to create.
This construct looks as follows (pseudo):
file_error = False
while not file_error:
written = False
while not written and not file_error:
try:
# attempt to write here
except size_error:
try:
# create new file using custom API
except creation_error:
file_error = True
else:
written = True
I didn't like how this was nested, so I took out the nesting:
file_error = False
while not file_error:
written = False
while not written and not file_error:
size_error_caught = False
try:
# attempt to write here
except size_error:
size_error_caught = True
else:
written = True
if size_error_caught:
try:
# create new file using custom API
except creation_error:
file_error = True
But then I thought, why bother nesting or adding another boolean variable, why not just try to do the work in the originally caught exception and add the previously nested exception to the same scope?:
file_error = False
while not file_error:
written = False
while not written and not file_error:
try:
# attempt to write here
except size_error:
# create new file using custom API
except creation_error:
file_error = True
else:
written = True
creation_error
s that happen in the# attempt to write here
block, exceptions thrown in the# create new file using custom API
block will not be caught by the code in your third attempt.try
block.