I think you need to try to separate the exceptions and handle them separately. A simple except Exception
is too broad. I have implemented a little example with your example code:
class WalkError(Exception):
pass
class MultiphotolabelsError(Exception):
pass
def my_function(some_input):
""" Process some_input. some_input may be a single object,
or a list-like iterable of the same.
More likely to be a list. """
dog = None # It is needed because dog variable could be undeclared.
photos = []
try:
for dog in some_input:
photos.append(walk(dog))
multiphotolabels(photos)
except (WalkError, MultiphotolabelsError) as err:
# I guess it was just one item after all
print("Exception: {}".format(err))
photos = walk(dog)
except Exception as unexpected_err:
print("Unexpected error. Error: {}".format(unexpected_err))
return photos
def walk(input_param):
if all(isinstance(item, str) for item in input_param):
return input_param
raise WalkError("Not all elem of list are string")
def multiphotolabels(input_param):
if len(input_param) > 1:
return
raise MultiphotolabelsError("Len of input is not greather than 1.")
print(my_function(["a", "b", "c"]))
print(my_function(["a", "b", "c", 5]))
print(my_function(["a"]))
As you can see I have handled separately the expected exceptions (WalkError, MultiphotolabelsError
) and the unexpected other errors are handler separately (except Exception as unexpected_err
)
Output of the script:
>>> python3 test.py
['a', 'b', 'c']
Unexpected error. Error: 'int' object is not iterable
['a', 'b', 'c']
Exception: Len of input is not greather than 1.
a
NOTE:
You implementation not really safety because the walk
function can generate recursive Exception
as you can see below:
Code:
print(my_function(["a", "b", "c", [8]]))
Output:
>>> python3 time.py
Exception: Not all elem of list are string
Traceback (most recent call last):
File "timeout.py", line 17, in my_function
photos.append(walk(dog))
File "timeout.py", line 31, in walk
raise WalkError("Not all elem of list are string")
__main__.WalkError: Not all elem of list are string
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "timeout.py", line 39, in <module>
print(my_function(["a", "b", "c", [8]]))
File "timeout.py", line 22, in my_function
photos = walk(dog)
File "timeout.py", line 31, in walk
raise WalkError("Not all elem of list are string")
__main__.WalkError: Not all elem of list are string
I hope my answer can help you!