Mayukh Sarkar
Mayukh Sarkar

Reputation: 2615

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.

Upvotes: 0

Views: 64

Answers (2)

Eevee
Eevee

Reputation: 48546

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

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798646

Your finally should be else, otherwise it will execute regardless of whether or not there was an exception.

Upvotes: 2

Related Questions