简体   繁体   English

尝试 - 除外行为

[英]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. 当我调用'checkarg'函数时,如果我没有在命令行上传递任何参数,我有“ERROR”输出和sys退出,正如预期的那样。

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. 但是,如果我在命令行上提供一个参数(如“-mycommand”),它会打印“SPECIFIC_TEXT”,然后从EXCEPT块打印“ERROR”消息。

The TRY block will only run when I provide a parameter, if I don't, then EXCEPT will get the turn. TRY块仅在我提供参数时运行,如果不提供,则EXCEPT将转弯。 But, it is running the TRY and EXCEPT blocks together. 但是,它正在运行TRY和EXCEPT块。

Does anybody knows the reason of this behavior?? 有谁知道这种行为的原因?? Any mistake on my code? 我的代码有什么错误吗? Tks for all ! Tks for all!

I think I understand your question... 我想我理解你的问题......

sys.exit() exits by raising a SystemExit exception, which your except statement is catching. sys.exit()通过引发您的except语句捕获的SystemExit异常退出。

Answer found here: http://docs.python.org/library/sys.html 答案在这里找到: http//docs.python.org/library/sys.html

sys.exit([arg]) sys.exit([参数])

Exit from Python. 退出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. 这是通过引发SystemExit异常来实现的 ,因此可以遵循try语句的finally子句指定的清除操作,并且可以拦截外层的退出尝试。

sys.exit works by raising an exception. sys.exit通过引发异常来工作。 That's why your except block executes. 这就是你的except块执行的原因。

You really shouldn't be using try / except for situations where you can check the state using control flow logic. 你真的不应该使用try / except ,你可以使用控制流逻辑来检查状态。

Instead, in this case, check for if len(sys.argv) > 1 . 相反,在这种情况下,检查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. except永远不会特别使用空白的另一个原因:您将捕获甚至系统异常,如SystemExitKeyboardInterrupt ,这使得它可能无法终止您的程序而不是凌乱的杀戮。

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; 我知道你已经接受了答案,但我认为问题的根源在于你的try块包含你不一定希望捕获异常的代码; 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. 为了解决这个问题,你的try块应该只包含filename=str(sys.argv[1]) ,你的try块中现在的其余代码应该被移动到一个else块,只有在没有异常发生时才会执行。 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 : 或者在这种情况下,由于您在异常情况下完全退出脚本,因此实际上并不需要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. 事实上,你正在用你的裸体捕捉每一个例外, except不好的风格和改变也会避免这个问题,但对我来说,它是次要的。 You do not wish to catch exceptions in your if/else code, so it should not be in the try block to begin with. 您不希望在if/else代码中捕获异常,因此它不应该在try块中开始。 IMHO, most admonitions against bare except would be moot if this guideline were followed more closely. 恕我直言, except更严格地遵循这一指导方针except ,对于裸露的大多数警告都没有实际意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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