Forbid forwarding or not re-raising a BaseException?

Common wisdom, as far as I know, is that not re-raising a BaseException (i.e. an exception that’s not an instance of Exception)is a coding error.

Is that (a) actually true (b) documented anywhere? 8. Errors and Exceptions — Python 3.13.7 documentation only states that you shouldn’t do it because BaseException instances are typically used to exit the program, which is incomplete (GeneratorExit, StopIteration, Cancelled …).

Maybe a better explanation is that those exceptions are used to unconditionally exit a particular scope (a generator or iterator, the whole program, an async task …) and thus must always be re-raised and not ignored (well, unless you 'really know what you’re doing …), and defintely should not be stored and then raised in a different context?

Replacing “program” with “scope” in the doc you quoted is probably reasonable, but there’s absolutely no reason at all to strengthen any of the statements here. Certainly nothing as strong as your post title suggests - I assume that was meant as clickbait (it worked, but only because people keep proposing unnecessary restrictions/limitations that cause nothing but pain, and I wish they’d just stop proposing them…)

No it’s not meant as clickbait; while perhaps I should have written “document that this is not a good idea unless you really know what you’re doing“, that simply was too long. :grinning_face_with_smiling_eyes:

A reasonably unequivocal statement that elaborates (somewhat) on the fact that that’s not how non-Exception BaseExceptions are supposed to be handled would be helpful IMHO — library code that assumes catching BaseException(and leaving the decision whether to re-raise them to a user-supplied exception handler) is a good idea isn’t that uncommon. I tend towards cleaning that up when I see it, and that’s easier when I can to point people to documentation saying so.

2 Likes