← index #1700PR #5032
Related · high · value 0.077
QUERY · ISSUE

Custom exception cannot be re-raised from called function

openby mbueschopened 2015-12-09updated 2026-03-18
docs

Consider this code:

class MyEx(Exception): pass

def do_raise():
        raise

try:
        raise MyEx()
except MyEx:
        try:
                do_raise()
        except MyEx:
                print("Ok")
        else:
                print("not Ok")

On MicroPython it fails with

Traceback (most recent call last):
  File "/home/mb/test.py", line 12, in <module>
  File "/home/mb/test.py", line 10, in <module>
  File "/home/mb/test.py", line 4, in do_raise
RuntimeError: No active exception to reraise

Things I noticed:
If the raise is done directly in the handler instead of do_raise, it works correctly (prints Ok).
If the exception is Exception instead of MyEx, it also works correctly.

CANDIDATE · PULL REQUEST

py: don't add traceback info for finally or re-raised exceptions

closedby dpgeorgeopened 2019-08-21updated 2019-08-28

This is a fix for #2928. It makes sure that traceback info is not added to exceptions that 1) propagate through a finally block; 2) are re-raised with raise (no args).

Eg, before this patch (see #2928 for the test script):

Traceback (most recent call last):
  File "<stdin>", line 19, in <module> (finally)
  File "<stdin>", line 17, in <module> (re-raise)
  File "<stdin>", line 17, in <module> (re-raise)
  File "<stdin>", line 14, in <module>
  File "<stdin>", line 2, in some_fn
  File "<stdin>", line 5, in foo
  File "<stdin>", line 8, in bar
RuntimeError: something

and after this patch:

Traceback (most recent call last):
  File "<stdin>", line 14, in <module>
  File "<stdin>", line 2, in some_fn
  File "<stdin>", line 5, in foo
  File "<stdin>", line 8, in bar
RuntimeError: something

(which matches CPython output).

I think this is a good fix, it will improve error messages (not as confusing), and make finally's slightly more efficient (in time and RAM) by not bothering to add the traceback.

The downside is that it increases code size a bit:

   bare-arm:   +28 +0.042% 
minimal x86:   +16 +0.010% 
   unix x64:   +32 +0.006% 
unix nanbox:   +96 +0.022% 
      stm32:   +20 +0.005% PYBV10
     cc3200:   +32 +0.017% 
    esp8266:   +56 +0.009% 
      esp32:   +24 +0.002% GENERIC
        nrf:   +16 +0.011% pca10040
       samd:   +24 +0.024% ADAFRUIT_ITSYBITSY_M4_EXPRESS

Also, it may reduce VM performance (when raising exception) by a tiny amount due to the extra checks, but I didn't yet measure that.

Keyboard

j / / n
next pair
k / / p
previous pair
1 / / h
show query pane
2 / / l
show candidate pane
c
copy suggested comment
r
toggle reasoning
g i
go to index
?
show this help
esc
close overlays

press ? or esc to close

copied