1

Could someone please explain the difference between -

def f():
    try:
        print('A', end=' ')
        raise ArithmeticError
    except:
        print('B', end=' ')
        raise AssertionError
    finally:
        print('C', end=' ')
        return

And

def f():
    try:
        print('A', end=' ')
        raise ArithmeticError
    except:
        print('B', end=' ')
        raise AssertionError
    finally:
        print('C', end=' ')
    return

The first code block does not raise any exceptions and print "A B C" while the second code block raises both exceptions and prints "A B C".

user3267989
  • 299
  • 3
  • 18
  • Does this answer your question? [Python try finally block returns](https://stackoverflow.com/questions/19805654/python-try-finally-block-returns) – ytan11 Dec 05 '21 at 06:52
  • @AppleBS - Well, I understand how finally works but I still don't get why I don't see any exceptions in the first case – user3267989 Dec 05 '21 at 09:36

1 Answers1

0

Because finally is guaranteed to be executed whether exception is raised or not.

Therefore, when you return in the finally block, you simply returned void and not the exception (or any other previously returned value).

Take this for example:

def f3():
    try:
        return "Try"
    finally:
        return "Finally"

When you print f3(), you will get Finally.

ytan11
  • 908
  • 8
  • 18