简体   繁体   English

为什么不能正确捕获异常?

[英]Why exception is not properly caught?

I have a piece of code. 我有一段代码。

import sys

while(True):
  print "Enter a number: "
  try:
    number = int(sys.stdin.readline())
  except ValueError:
    print "Error! Enter again an integer value"
    continue
  finally:
    print number
    break

Here I expect when I enter a non-integer number, the output should be 在这里,我希望当我输入一个非整数时,输出应该是

Error! Enter again an integer value

and then it should ask for input. 然后它应该要求输入。 But it is printing the message but asking for further inputs. 但是它正在打印消息,但要求进一步输入。 Please explain it or if am thinking it wrong. 请解释一下,或者认为有误。

If I handle with NameError, then error message is not even being printed and the program is exiting with a traceback call. 如果我使用NameError进行处理,则错误消息甚至都不会被打印,并且该程序将通过回溯调用退出。

您的finally应该为else ,否则它将执行,无论是否存在异常。

The finally clause always runs, whether an exception was caught or not. 无论是否捕获到异常, finally子句始终运行。 You want else , which runs when there was no exception. 您需要else ,它在没有异常的情况下运行。

Also: you don't need parentheses for a while , and you probably want the raw_input function which is a little nicer to use than messing with sys.stdin directly. 另外:你不需要括号的while ,你可能想raw_input函数,它是一个更好一点比搞乱使用sys.stdin直接。

So I would do: 所以我会做:

while True:
    try:
        number = int(raw_input("Enter a number: "))
    except ValueError:
        print "Error! Enter again an integer value"
        continue
    else:
        print number
        break

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

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