What is the super-class of Exception in Python? Please provide me the Python exception hierarchy.
Is there any Exception super-class, like Throwable of Java Exception, in Python?
3.1k Views Asked by Akshay Sharma At
2
There are 2 best solutions below
1
On
Exception's base class:
>>> Exception.__bases__
(BaseException,)
Exception hierarchy from the docs confirms that it is a base class for all exceptions:
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- ArithmeticError
| +-- FloatingPointError
...
The syntax to catch all exceptions is:
try:
raise anything
except:
pass
NOTE: use it very very sparingly e.g., you could use it in a __del__ method during cleanup when the world might be half-destroyed and there is no other alternative.
Python 2 allows to raise exceptions that are not derived from BaseException:
>>> raise 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: exceptions must be old-style classes or derived from BaseException, not int
>>> class A: pass
...
>>> raise A
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
__main__.A: <__main__.A instance at 0x7f66756faa28>
It is fixed in Python 3 that enforces the rule:
>>> raise 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: exceptions must derive from BaseException
You are looking for
BaseException.User defined exception types should subclass
Exception.See the docs.