Reputation: 69
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.
Upvotes: 2
Views: 9379
Reputation: 93
If you're looking to raise a The following code will produce a Syntax Error, EOF in Python:
print("Where's EOF now?")
#### this is a test to see where the EOF occurs... suspect is that it will be EOF line 4
print("Hello world!"
I'm not sure if this is what you mean by "raise an error", though. Creates a new post in StackOverflow
Upvotes: 0
Reputation: 531265
You caught the exception, meaning Python will continue with the loop instead of letting the exception percolate up the stack, ultimately ending the program if it remains uncaught. Calling raise
without an argument in an except
clause simply raises the same exception again, equivalent to
except EOFError as exc:
print("Unexpected error")
raise exc
Re-raising the exception is necessary if you don't actually handle the exception, instead simply adding additional logging before (possibly) someone else handles it.
Triggering the EOFError
can be done by running
$ python -c 'input()' < /dev/null
Traceback (most recent call last):
File "<string>", line 1, in <module>
EOFError: EOF when reading a line
as all attempts to read from /dev/null
look like an attempt to read from the end of a file.
Upvotes: 2
Reputation: 106598
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
Upvotes: 5