Alex Rivera | Logout

Python: User-Defined Exception That Proves The Rule

Asked 2010-05-08T10:59:15.220
13

Python documentations states:

Exceptions should typically be derived from the Exception class, either directly or indirectly.

the word 'typically' leaves me in an ambiguous state.

consider the code:

class good(Exception): pass
class bad(object): pass

Heaven = good()
Hell = bad()

>>> raise Heaven

Traceback (most recent call last):
  File "<pyshell#163>", line 1, in <module>
    raise Heaven
good

>>> raise Hell

Traceback (most recent call last):
  File "<pyshell#171>", line 1, in <module>
    raise Hell
TypeError: exceptions must be classes or instances, not bad

so when reading the python docs, should i replace 'typically' with ''?

what if i have a class hierarchy that has nothing to do with the Exception class, and I want to 'raise' objects belonging to the hierarchy?

I can always raise an exception with an argument:

raise Exception, Hell

This seems slightly awkward to me

What's so special about the Exception (EDIT: or BaseException) class, that only its family members can be raised?

Edit
Report

1 Answer

22

There are other valid classes you can inherit from apart from Exception, for example BaseException.

See the documentation for the exception hierarchy.

BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StandardError
      etc..

In older versions of Python it was possible to throw things other than exceptions. For example in Python 2.5:

>>> raise "foo"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
foo

But you get this deprecation warning:

DeprecationWarning: raising a string exception is deprecated

In newer versions this is not allowed. Everything you raise must derive from BaseException.

answered 2010-05-08T11:05:09.873

Your Answer