Re-raising the exception doesn't work with "finally" clause

exception, python

Solution

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.

Problem

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 :)

Original source

Related problems