Your Ad could be here. I want to connect my readers to relavant ads. If you have a product targeted at developers, let's talk. [email protected]
I ran into a PR this week where the author was inheriting what BaseException rather than exception. I made this example to illustrate the unintended side effects that it can have.
Try running these examples in a
.py file for yourself and try to kill them
Since things such as
KeyboardInterrupt are created as an exception that
BaseException, if you except
BaseException you can no longer
from time import sleep while True: try: sleep(30) except BaseException: # ❌ pass
If you except from exception or something than inherits from it you will be better off, and avoid unintended side effects.
from time import sleep while True: try: sleep(30) except Exception: # ✅ pass
When you make custom exceptions expect that users, or your team members will
want to catch them and try to handle them if they can. If you inherit from
BaseException you will put them in a similar situation when they use your
class MyFancyException(BaseException): # ❌ ... class MyFancyException(Exception): # ✅ ...