Consider the following code:
try: raise Exception("a") except: try: raise Exception("b") finally: raise
This will raise Exception: a
. I expected it to raise Exception: b
(need I explain why?). Why does the final raise
raise the original exception rather than (what I thought) was the last exception raised?
Python raise Keyword is used to raise exceptions or errors. The raise keyword raises an error and stops the control flow of the program. It is used to bring up the current exception in an exception handler so that it can be handled further up the call stack.
The RAISE statement stops normal execution of a PL/SQL block or subprogram and transfers control to an exception handler. RAISE statements can raise predefined exceptions, such as ZERO_DIVIDE or NO_DATA_FOUND , or user-defined exceptions whose names you decide.
Sometimes you want Python to throw a custom exception for error handling. You can do this by checking a condition and raising the exception, if the condition is true. The raised exception typically warns the user or the calling application.
Raise is re-raising the last exception you caught, not the last exception you raised
(reposted from comments for clarity)
On python2.6
I guess, you are expecting the finally block to be tied with the "try" block where you raise the exception "B". The finally block is attached to the first "try" block.
If you added an except block in the inner try block, then the finally block will raise exception B.
try: raise Exception("a") except: try: raise Exception("b") except: pass finally: raise
Output:
Traceback (most recent call last): File "test.py", line 5, in <module> raise Exception("b") Exception: b
Another variation that explains whats happening here
try: raise Exception("a") except: try: raise Exception("b") except: raise
Output:
Traceback (most recent call last): File "test.py", line 7, in <module> raise Exception("b") Exception: b
If you see here, replacing the finally block with except does raise the exception B.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With