Problem with EOFError Exception

This is the place for queries that don't fit in any of the other categories.

Problem with EOFError Exception

Postby stdq » Tue Jul 30, 2013 12:16 am

Hi, everyone. This is not a homework exercise. I wrote a program that asks for an integer, and displays it raised to 2, 3 and 4. However, I am having problems in handling the EOFError exception for when I enter Ctrl + Z - the program still finishes and the name of the exception is printed. The ValueError exception is handled correctly, though. What am I doing wrong? Thanks in advance.

Code: Select all
line = input( 'Please enter an integer: ' )

while True:
    try:
        integer = int( line )
        break
    except EOFError:
        print( '\nAn invalid integer was entered.' )
        line = input( 'Please enter another value: ' )
    except ValueError:
        print( '\nAn invalid integer was entered.' )
        line = input( 'Please enter another value: ' )

print( '\nSquare of %d:       %d.' % ( integer, integer * integer ) )
print( 'Cube of %d:         %d.' % ( integer, integer * integer * integer ) )
print( 'Fourth power of %d: %d.' % ( integer, integer ** 4 ) )
stdq
 
Posts: 4
Joined: Tue Jul 23, 2013 10:04 pm

Re: Problem with EOFError Exception

Postby Mekire » Tue Jul 30, 2013 1:30 am

The place where you get the input must be within the try block.

Code: Select all
while True:
    try:
        line = input('Please enter an integer: ')
        integer = int( line )
        break
    except EOFError:
        print("EOFError")
        print( '\nAn invalid integer was entered.' )
    except ValueError:
        print( '\nAn invalid integer was entered.' )

print( '\nSquare of %d:       %d.' % ( integer, integer * integer ) )
print( 'Cube of %d:         %d.' % ( integer, integer * integer * integer ) )
print( 'Fourth power of %d: %d.' % ( integer, integer ** 4 ) )

Not sure why you want to stop the user from doing that though. Emergency methods of shutting down programs shouldn't generally be overridden.

-Mek
User avatar
Mekire
 
Posts: 988
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan

Re: Problem with EOFError Exception

Postby stdq » Tue Jul 30, 2013 4:17 pm

Good point. Thanks!
stdq
 
Posts: 4
Joined: Tue Jul 23, 2013 10:04 pm


Return to General Coding Help

Who is online

Users browsing this forum: Baidu [Spider], W3C [Linkcheck] and 2 guests