Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try block inside while statement

I'm just starting out with Python 2.7 and I don't understand why something is happening:

In the following code, an embellished version of an example from the python 2.7.2 tutorial, I get an unexpected result:

while True:
    try:
        x = int(raw_input("Please enter a number: "))
        break
    except ValueError:
        print "Oops!  That was not a valid number.  Try again..."
    else:
        print 'Thanks,',x,'is indeed an integer'
    finally:
        print 'all done, bye'

When I put in an integer, the code ignores the else: statement and cuts straight to finally:. Clearly it's something to do with the while True: at the top but why is it happening?

like image 405
user1568416 Avatar asked Aug 01 '12 11:08

user1568416


People also ask

What kind of statements are put inside the try block?

Place any code statements that might raise or throw an exception in a try block, and place statements used to handle the exception or exceptions in one or more catch blocks below the try block. Each catch block includes the exception type and can contain additional statements needed to handle that exception type.

Can we use try inside try block?

In Java, using a try block inside another try block is permitted. It is called as nested try block.

Can I put try catch inside for loop?

One way to execute the loop without breaking is to move the code that causes the exception to another method that handles the exception. If you have try catch within the loop it gets executed completely inspite of exceptions.

Can try block have multiple statements?

You cannot have multiple try blocks with a single catch block. Each try block must be followed by catch or finally. Still if you try to have single catch block for multiple try blocks a compile time error is generated.


1 Answers

The break statement is pulling out of the loop, so the else statement will never be reached.

Put the break in the else clause instead, like so:

while True:
    try:
        x = int(raw_input("Please enter a number: "))
    except ValueError:
        print "Oops!  That was not a valid number.  Try again..."
    else:
        print 'Thanks,',x,'is indeed an integer'
        break

print 'all done, bye'
like image 142
Sherlock Avatar answered Oct 18 '22 20:10

Sherlock