Home > Blockchain >  Python Nested Recursion for multi condition exception handling
Python Nested Recursion for multi condition exception handling

Time:09-19

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

CodePudding user response:

**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

    
        

CodePudding user response:

I think you are doing fine according to EAFP

  • Related