Akshay Sharma
Akshay Sharma

Reputation: 97

Is there any Exception super-class, like Throwable of Java Exception, in Python?

What is the super-class of Exception in Python? Please provide me the Python exception hierarchy.

Upvotes: 2

Views: 3321

Answers (2)

jfs
jfs

Reputation: 414585

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

Upvotes: 6

shx2
shx2

Reputation: 64328

You are looking for BaseException.

User defined exception types should subclass Exception.

See the docs.

Upvotes: 5

Related Questions