Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does raise in Python raise?

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?

like image 770
wilhelmtell Avatar asked Oct 14 '10 17:10

wilhelmtell


People also ask

What does raise () do in Python?

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.

What does raise statement allows?

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.

What is raising an error Python?

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.


2 Answers

Raise is re-raising the last exception you caught, not the last exception you raised

(reposted from comments for clarity)

like image 155
2 revs, 2 users 73% Avatar answered Sep 22 '22 22:09

2 revs, 2 users 73%


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.

like image 30
pyfunc Avatar answered Sep 25 '22 22:09

pyfunc