简体   繁体   中英

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.

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

The finally clause always runs, whether an exception was caught or not. You want else , which runs when there was no exception.

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.

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

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