[SOLVED] Python finally block not catching errors

Issue

Take a look at a chunk of code:

move = [None, 20, 5, True, "a"]   
valnum = 0
    for val in move:
        try:
            if val >= 15:
                val -= 3
                move[valnum] = val
        finally:
            valnum += 1
print(move)

When run, it gives this error:

TypeError: '>=' not supported between instances of 'NoneType' and 'int'

Isn’t the whole point of the finally statement to avoid errors like this?

EDIT: Thank you for your help. I don’t think I made myself clear enough in my question. After your suggestions, I coded it to this:

move = [None, 20, 5, True, "a", 19]   
valnum = 0
for val in move:
    try:
        if val >= 15:
            val -= 3
            move[valnum] = val
    except TypeError:
        valnum += 1
print(move)

And the output now becomes:

[None, 17, 16, True, 'a', 19]

It’s easy to see what went wrong. The exception block only runs when there is an error, but I need the block to run no matter if there is an error or not. Is there a solution to this, other than just:

move = [None, 20, 5, True, "a", 19]   
valnum = 0
for val in move:
    try:
        if val >= 15:
            val -= 3
            move[valnum] = val
    except TypeError:
        valnum += 1
        continue
    valnum += 1
print(move)

Solution

No, it is not.

It is there to make sure something always gets executed, no matter if there is an exception or not. It does not catch the exception, for that you need an except block.

For example:

for val in move:
    try:
        if val >= 15:
            val -= 3
            move[valnum] = val
    except TypeError:
        valnum += 1

finally blocks are useful for things like resource cleanup, closing files, that sort of thing.


Based on the comment by Big Bird, here is how you would run the code and also ignore the error:

for val in move:
    try:
        if val >= 15:
            val -= 3
            move[valnum] = val
    except TypeError:
        pass  # catch the error and ignore it
    valnum += 1

Edited yet again, I realised what you wanted to do only now, since I’d been too focussed on how you were trying to do it. I suggest not caring about valnum at all, instead doing this:

move = [None, 20, 5, True, "a", 19]   
for index, val in enumerate(move):
    try:
        if val >= 15:
            val -= 3
            move[index] = val
    except TypeError:
        pass
print(move)

Answered By – Jasmijn

Answer Checked By – Jay B. (BugsFixing Admin)

Leave a Reply

Your email address will not be published.