简体   繁体   中英

quit function does not work in try-except block

this is quit function that ı want to run it in the try except block..

def quit_function(quit):
     if(quit=="quit"):
        sys.exit(1)

when I enter correct input it works function_one but when I write "exit" in order to exit the program quit_function doesn't work, the except part works so output is "invalid input"..how can I fix it?

 while True:
    try:
        a=raw_input("Enter input :").lower()
        function_one(a)
        quit_function(a)
    except:
        print "invalid input"
    else:
        break

exit raises a SystemExit , which inherits from BaseException .

You are catching the exit in your except block. Try making the except more specific, to only catch normal exceptions (not exit signals):

try:
   ...
except Exception:
   print "Invalid input"

Better yet, figure out the actual specific type of exception you need to catch and only catch that.

The sys.exit function actually raises a special SystemExit exception, which will propogate up the stack, executing finally blocks of try statements as it goes, until the exception gets caught or reaches the top of the stack. In the latter case, python cleanly exits, rather than printing a traceback. To avoid catching the SystemExit exception, change your bare except statement to except Exception or something more specific. Or, if you really need to exit immediately without excpetion handlers running , you can use os._exit

I am going to assume when I write "exit" actually meant when I write "quit" since your function looks for the string "quit" .

First since you have a generic except block, you aren't seeing what the actual Exception is so I am going to bet that function_one("quit") throws an Exception . You need to process quit_function() before function_one() .

Second, sys.exit() also throws a specialized type of exception so except: isn't going to cut it.

Something along these lines should work:

while True:
    try:
        a=raw_input("Enter input :").lower()
        quit_function(a)
        function_one(a)
    except Exception:
        print "invalid input"
    else:
        break

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM