raddirad
raddirad

Reputation: 331

Python: nested try catch handling

currently I have some code like this

try:
    somecode
except Exception as Error:
    fallbackcode

Now i want to add another fallback to the fallbackcode Whats is the best practice to make a nested try/catch in python?

try:
    somecode
except Exception as Error:
    try:
        fallbackcode
    except Exception as Error:
        nextfallbackcode

produces intendation errors

Upvotes: 1

Views: 9842

Answers (4)

Abhijit
Abhijit

Reputation: 63717

You can rewrite the logic using a loop provided all your callbacks and fallbacks have same API interface

for code in [somecode, fallbackcode, nextfallbackcode]:
    try:
        code(*args, **kwargs)
        break
    except Exception as Error:
        continue
else:
    raise HardException

This would be the preferred way instead of multiple level of nested exception blocks.

Upvotes: 3

kederrac
kederrac

Reputation: 17322

you can use functions to handle errors :

def func0():
    try:
        somecode
    except:
        other_func()

def func1():
    try:
        somecode
    except:
        func0()

Upvotes: 2

Santhosh Kumar
Santhosh Kumar

Reputation: 543

You could have change it like this:

try:
    try:
        somecode
    except Exception as Error:
        fallbackcode
except Exception as Error:
    nextfallbackcode

Upvotes: 0

AlanK
AlanK

Reputation: 9833

You should be able to do nested try/except blocks exactly how you have it implemented in your question.

Here's another example:

import os

def touch_file(file_to_touch):
    """
    This method accepts a file path as a parameter and
    returns true/false if it successfully 'touched' the file
    :param '/path/to/file/'
    :return: True/False
    """    
    file_touched = True

    try:
        os.utime(file_to_touch, None)
    except EnvironmentError:
        try:
            open(file_to_touch, 'a').close()
        except EnvironmentError:
            file_touched = False

    return file_touched

Upvotes: 5

Related Questions