Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why should we use Exception as a superclass, why not BaseException

In python, whenever we are writing User-defined exception, we have to extend it from class Exception. my question is why can't we extend it from BaseException which is super-class of exception hierarchy and Exception is also subclass of BaseException.

like image 367
tailor_raj Avatar asked Jul 23 '13 05:07

tailor_raj


2 Answers

BaseException includes things like KeyboardInterrupt and SystemExit, which use the exception mechanism, but which most people shouldn't be catching. It's analogous to Throwable in Java, if you're familiar with that. Things that derive directly from BaseException are generally intended to shut down the system while executing finally blocks and context manager __exit__ methods to release resources.

like image 93
user2357112 supports Monica Avatar answered Sep 21 '22 21:09

user2357112 supports Monica


Per the Python2 documentation, there are four exceptions that are derivatives of BaseException:

BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception

The three that are not Exception are not actually errors, which means in general you don't want to catch them as if they are errors. BaseException was added in Python2.5 (before that, there was no BaseException and the other exceptions were subclassed from Exception).

like image 42
torek Avatar answered Sep 24 '22 21:09

torek