Home > Enterprise >  How to stop the program once a return value of None is recieved?
How to stop the program once a return value of None is recieved?

Time:01-25

my problem is my code has this structure: as you can see the second function depends on the outcome of the first. but I want the program to end when the first function catches an error but what I get is, it displays the exception message of the first function and it proceeds to the next step of the main function by assuming the first function gave it a None value which causes a Type error which I don't want. what should I do? PS: assume that i have 40 functions which depend up on each other like the ones below upto 'func50'

def func1(input1):
    try:
        table = []
        #some stuffs here which append to table       
        return table
    except IOError:
        print("try again")
def func2(formatted_file):
    try:
        val = {}
        #some stuffs here
        return val
    except IndexError:
        print("index error")
def main():
    input1 = input("insert val")
    formatted_file = func1(input1)
    mine = funct2(formatted_file)
    print(mine)
main()

CodePudding user response:

Use sys.exit() in your except block to stop the code from progressing, otherwise the print() is the only action in case of the try: not working.

CodePudding user response:

There is no IOError. The list remains empty. The given code is an edited version of your code. Change try-except to if table is empty set and rasies a system exit if condition is true


def func1(input1):
        table = []

        #some stuffs here which append to table
        if table == []:
            print('try again')
            raise SystemExit(0)
        return table

def func2(formatted_file):
    try:
        val = {}
        #some stuffs here
        return val
    except IndexError:
        print("index error")
def main():
    input1 = input("insert val")
    formatted_file = func1(input1)
    mine = func2(formatted_file)
    print(mine)
main()```
  •  Tags:  
  • Related