Exception objects and lists. Here's the way we extended this module for an exception of our own (here a string, at first):
MyError = 'hello' def oops( ): raise MyError, 'world' def doomed( ): try: oops( ) except IndexError: print 'caught an index error!' except MyError, data: print 'caught error:', MyError, data else: print 'no error caught...' if __name__ == '__main__': doomed( ) % python oops.py caught error: hello world
To identify the exception with a class, we just changed the first part of the file to this, and saved it as oop_oops.py:
class MyError: pass def oops( ): raise MyError( ) ...rest unchanged...
Like all class exceptions, the instance comes back as the extra data; our error message now shows both the class, and its instance (<...>).
% python oop_oops.py caught error: __main__.MyError <__main__.MyError instance at 0x00867550>
Remember, to make this look nicer, you can define a __repr__ or __str__ method in your class to return a custom print string. See Chapter 21 for details.