简体   繁体   中英

Try-Except Behavior

import sys  

def checkarg():  
    try:  
        filename=str(sys.argv[1])  
        if filename=="-mycommand":  
            print "SPECIFIC_TEXT"  
            sys.exit()  
        else:    
            return filename  
    except:  
        print "ERROR"  
        sys.exit()

Hello all...i have a problem with the code above. When i call the 'checkarg' function, if i did not pass any parameter on the command line i have the "ERROR" output and sys exit, just as expected.

But, if i provide a parameter on the command line (like "-mycommand") it prints the "SPECIFIC_TEXT" and then prints "ERROR" message from the EXCEPT block too.

The TRY block will only run when I provide a parameter, if I don't, then EXCEPT will get the turn. But, it is running the TRY and EXCEPT blocks together.

Does anybody knows the reason of this behavior?? Any mistake on my code? Tks for all !

I think I understand your question...

sys.exit() exits by raising a SystemExit exception, which your except statement is catching.

Answer found here: http://docs.python.org/library/sys.html

sys.exit([arg])

Exit from Python. This is implemented by raising the SystemExit exception , so cleanup actions specified by finally clauses of try statements are honored, and it is possible to intercept the exit attempt at an outer level.

sys.exit works by raising an exception. That's why your except block executes.

You really shouldn't be using try / except for situations where you can check the state using control flow logic.

Instead, in this case, check for if len(sys.argv) > 1 .

Another reason never to use specifically a blank except : You will catch even system exceptions like SystemExit or KeyboardInterrupt , making it potentially impossible to terminate your program short of a messy kill.

I know you've already accepted an answer, but I think the root of the problem is that your try block contains code in which you do not necessarily wish to catch exceptions; rather, you merely wish these statements to be executed after the code in which you wish to catch exceptions if no exception occurs.

To address this, your try block should contain only filename=str(sys.argv[1]) and the rest of the code now in your try block should be moved to an else block, which will be executed only if no exception occurs. In other words:

try:  
    filename=str(sys.argv[1])  
except:  
    print "ERROR"  
    sys.exit()
else:
    if filename=="-mycommand":  
        print "SPECIFIC_TEXT"  
        sys.exit()  
    else:    
        return filename  

Or in this case, since you exit the script entirely in the case of an exception, you don't actually need the else :

try:  
    filename=str(sys.argv[1])  
except:  
    print "ERROR"  
    sys.exit()
if filename=="-mycommand":  
    print "SPECIFIC_TEXT"  
    sys.exit()  
else:    
    return filename  

The fact that you're catching every exception with your bare except is bad style and changing that would also avoid the problem, but to me, it's secondary. You do not wish to catch exceptions in your if/else code, so it should not be in the try block to begin with. IMHO, most admonitions against bare except would be moot if this guideline were followed more closely.

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