5

When I put in a finally clause, the raise statement in except doesn't work.

So the except block doesn't produce an Exception.

What am I missing? What do I need to do if I want to re-raise the Exception after the finally clause returns the value?

def test():
    res = 1
    try:
            raise Exception
            res = 2
    except:
            print('ha fallado')
            raise

    finally:
            return res
test()

Solution:

def test():
    res = 1
    try:
            raise Exception
            res = 2
    except:
            print('ha fallado')
            raise

    finally:
            # ... finally code that need to exec
            pass

    return res

print(test())

In this way if a Exception happened, the except block handle the exception and then raise it.

If not exception happened return the value.

Thanks for all the answers! So quick :)

Géminis
  • 123
  • 2
  • 9

2 Answers2

8

Here is an answer that quotes the relevant part of the documentation:

The try clause is executed, including any except and else clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally clause is executed. If there is a saved exception it is re-raised at the end of the finally clause. If the finally clause raises another exception, the saved exception is set as the context of the new exception. If the finally clause executes a return or break statement, the saved exception is discarded:

>>> def f():
...     try:
...         1/0
...     finally:
...         return 42
...
>>> f()
42

P.S. I don't quite understand what you actually want to achieve; as noted in the top answer linked by zmbq, you can't really have both.

Community
  • 1
  • 1
Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
  • Thanks for the answer. I got it, I needed to return my value if no exception happened and before code that closes connections etc. I will edit the post with the fix to help other people. – Géminis May 07 '17 at 11:54
2

That's because you put a return statement in the finally block. It means you really want to return a value, even if an exception is thrown.

See here for more information.

Community
  • 1
  • 1
zmbq
  • 38,013
  • 14
  • 101
  • 171