Python Forum

Full Version: is try/except safe inside of another except?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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,).
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
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
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 exception
with 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 data
it'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
with break, now that makes more sense.
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