Home > Mobile >  Python finally block not catching errors
Python finally block not catching errors

Time:02-14

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?

CodePudding user response:

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.

CodePudding user response:

What you want to use is 'except' for handling that. Your code should look like:

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

When you use finally, it means that the code inside finally will run after the try condition as a clean-up action. You can check the documentation for more information on the finally action: https://docs.python.org/3/tutorial/errors.html#defining-clean-up-actions

Looking at your code and use, you can simply

  • Related