Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try-Except Behavior

Tags:

python

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 !

like image 829
StarkBR Avatar asked Feb 10 '26 13:02

StarkBR


1 Answers

I think I understand your question...

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

like image 72
Bill Lynch Avatar answered Feb 13 '26 07:02

Bill Lynch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!