Search code examples
pythonexcept

Return part of result if occur a except


I am using python. I have a function (getAll) that call other function in a loop (getPart) and in each step the return value is updated. In some case when I call the function that is inside the loop, this fail. I need return the result in this moment.

def getAll(m, d, v, t, s, tn, type):
  result = []
  flag = 0
  while flag == 0:
    tempResult = getPart(m, d, v)
    for i in range(0, len(tempResult)):
      result.append(tempResult[i])
    flag = tempResult[0]
  return result

print getAll(5,4,1,'ds',8,'data')

I need print the result partial value, if occur a except in some step when I call tempResult in getAll


Solution

  • Sounds like you need to use try, except blocks

    def getAll(m, d, v, t, s, tn, type):
        result = []
        flag = 0
        while flag == 0:
            try: #start of the try block. 
                tempResult = getPart(m, d, v)
                for i in range(0, len(tempResult)):
                    result.append(tempResult[i])
                flag = tempResult[0]
            except: #handle what ever errors comes here
                return tempResult
        return tempResult
    

    Basically when you catch an error or an error is raised it will run what ever is in the except block, since we are putting return tempResult it will return the value.

    Like the comment says, catching all exceptions is a bad idea since you might hit an error that has nothing to do with your code and it will catch it, for specific exceptions you should do:

    try:
        #do something
    except <Error name like "ValueError">
        #handle it
    

    You can also see more error details like:

    try:
        #do something
    except ValueError as e:
        #handle it
        print(e) #prints the error
    

    So find out what errors will cause your program to stop and put it there.