![]() |
is try/except safe inside of another except? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: is try/except safe inside of another except? (/thread-20269.html) |
is try/except safe inside of another except? - Skaperen - Aug-03-2019 is it safe to have a try/except within the except of another try/except? i want to get some data that may fail, resulting in an exception. then there is an alternate place to get it and that, too, may throw an exception. then there is even a 3rd place that may throw an exception. if any work, tried in that specific order, of course i want to return the data. else i want to return n*(None,). RE: is try/except safe inside of another except? - scidam - Aug-04-2019 Maybe I something misunderstand, but you can iterate over data locations, e.g. something like this: def func(): data = None for place in places: try: data = get_data_from_place(place) except CustomException: # or exceptions pass return data RE: is try/except safe inside of another except? - Skaperen - Aug-04-2019 i mean something like: try: ... something that could raise an exception except the_exception_to_deal_with: try: ... the handler that could raise a different exception except the_different_exception: ... the handler for the 2nd exception RE: is try/except safe inside of another except? - buran - Aug-04-2019 compare try: # first source ... something that could raise an exception except the_exception_to_deal_with: try: # second source ... the handler that could raise a different exception except the_different_exception: try: # third source ... the handler that could raise a different exception except the_different_exception: ... the handler for the 3rd exceptionwith what scidam suggested (I just added the break )def get_data(places): data = None for place in places: try: data = get_data_from_place(place) break # will ne executed if no exception, i.e. respective place returned data except SomeException: # or exceptions pass return datait's more readable and you can have any number of places to look at without any additional code/extra levels you may pair place and exception if by chance different places raise different exception RE: is try/except safe inside of another except? - Skaperen - Aug-04-2019 with break, now that makes more sense. RE: is try/except safe inside of another except? - buran - Aug-04-2019 if you prefer without break def get_data(places): for place in places: try: data = get_data_from_place(place) except Exception: # use specific exception or exceptions continue else: return data |