I am a newbie learning python. Please take a look at the below code (From Data Structures and Algorithms in Python by Goodrich, et al).
age = -1 # an initially invalid choice
while age <= 0:
try:
age = int(input('Enter your age in years: '))
if age <= 0:
print('Your age must be positive.')
except ValueError:
print('That is an invalid age specification.')
except EOFError:
print('There was an unexpected error reading input.')
raise # let's re-raise this exception.
I know what ValueError is. For example the ValueError occurs if the input is given as characters instead of an integer.
On the other hand, I have no idea when EOFError raises.
I can't get what 're-raise this exception' means
The book says, 'the call to input will raise an EOFError if the console input fails.' Again, I have no idea what console input is and when console input fails.
I have tried several ways of raising EOFError, but every time I tried there was only ValueError. Can someone give me some idea?
Thanks in advance.
From input
's documentation:
When
EOF
is read,EOFError
is raised.
EOF
is sent when the input stream reaches the end, or if it's from the console, it means the user presses ctrl-D on *NIX, or ctrl-Z on Windows.
You can catch the EOFError
exception and break your while
loop as a way to end the program gracefully, so change your exception block to:
except EOFError:
print('Done.')
break