Except Finally - Operator

176 Views Asked by At

i have an curious Question regarding except Block, especially finally:

During the first Block of Code finally works as it is supposed to work, meanwhile in second which is minimaly different from the first one it always gives you an error.

First:

def askint():
while True:
    try:
        val = int(raw_input("Please enter an integer: "))
    except:
        print "Looks like you did not enter an integer!"
        continue
    else:
        print 'Yep thats an integer!'
        break
    finally:
        print "Finally, I executed!"
    print val 

Second:

def Abra():
while True:
    try:
        v  = int(raw_input('Geben Sie bitte einen Integer ein (1-9) : '))
    except :
        print 'Einen Integer bitte (1-9)'
        continue

    if v not in range(1,10):
        print ' Einen Integer von 1-9'
        continue
    else:
        print 'Gut gemacht'
        break
    finally:
        print "Finally, I executed!"

Abra()

Open for all solutions - Thanks

2

There are 2 best solutions below

0
On

The finally clause must be directly connected to the try/except clause in order for it to work. In the second block of code, there is an if/else in between the try/except and the finally. Thus, the structure is try/except, if/else, finally, which is invalid. In the first, by contrast, the else is a block that executes when the exception is not raised and is thus part of the try/except - the structure is try/except/else/finally.

2
On

I believe the confusion you've got is from the else in the first example.

In a "try/except" block the areas try, except, else and finally are all valid. This can be misleading to a new programmer, as the else is not the same else as an if statement.

You can read about it here: Python try-else

In your second example, the if statement is out of place as it should be either outside of the entire try/except/else/finally block, or indented into one of the sections correctly.

For your specific example, you'll want something similar to this:

def Abra():
    while True:
    try:
        v  = int(raw_input('Geben Sie bitte einen Integer ein (1-9) : '))
        if v not in range(1,10):
            print ' Einen Integer von 1-9'
            continue
    except :
        print 'Einen Integer bitte (1-9)'
        continue
    else:
        print 'Gut gemacht'
        break
    finally:
        print "Finally, I executed!"

Although, I might suggest you would just remove the else to avoid confusion to yourself (but this is a argument better discussed in the link above):

def Abra():
    while True:
    try:
        v  = int(raw_input('Geben Sie bitte einen Integer ein (1-9) : '))
        if v not in range(1,10):
            print ' Einen Integer von 1-9'
            continue
        print 'Gut gemacht'
        break
    except :
        print 'Einen Integer bitte (1-9)'
        continue
    finally:
        print "Finally, I executed!"