Python Nested Recursion for multi condition exception handling

Viewed 66

I have 3 conditions C1,C2,C3 which are to be checked. If C1 gives a timeout exception, try C2. If C2 gives a timeout exception, try C3. If C3 gives timeout Exception, return None for the function. But if any of C1, C2, C3 is success, execute rest of the code in the function.

I am using nested try catch blocks as below, but not sure if this is the correct way. Please suggest the best Pythonic approach.

def func():
  try:
    C1
  except:
    try:
      C2
    except:
      try:
        C3
      except:
         return None
  
  try:
    ** Rest of the Code **
    return someValue
  except:
    return None
3 Answers
**You can follow this approach**
def func():
    if CheckC1() or CheckC2() or CheckC3() :
        try:
        ** Rest of the Code **
            return someValue
        except:
            return None
    return None

def CheckC1():
    try:
        C1
        return true
    except:
        return false

def CheckC2():
    try:
        C2
        return true
    except:
        return false

def CheckC3():
    try:
        C3
        return true
    except:
        return false

    
        

I think you are doing fine according to EAFP

And I think you can use decorators too:

def C1(func):
    def wrapper():
        try:
            raise Exception('spam', 'eggs')
            print("C1")
            
            print("C1")
        except:
            return func()
            
    return wrapper

def C2(func):
    def wrapper():
        try:
            
            print("C2")

            print("C2")
        except:
            return func()
    return wrapper

def C3(func):
    def wrapper():
        try:
             
            print("C3")

            print("C3")
        except:
            return func()
    return wrapper

@C1
@C2
@C3
def myFunc():
    return 'hi'



myFunc()

Output:

C2
C2

I would suggest doing it in a for loop:

def func():
    for c in (C1, C2, C3):
        try:
            c
            break
        except Your_Exception_Here:
            continue
    else:
        return None

    # Rest of the code

the else part of the for-loop is only gonna get executed if all of those three condition raise exception. If any of them succeeds, for loop breaks and the rest of the code executes.

Related