Search code examples
pythonexceptionconditional-statementstry-except

Python Nested Recursion for multi condition exception handling


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

Solution

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