12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

if _ _name_ _ == '_ _main_ _': doomed( )% python oops.pycaught an index error!2. Exception objects and lists. Here’s the way I extended this module for an exceptionof my 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, dataelse:print 'no error caught...'if _ _name_ _ == '_ _main_ _':doomed( )% python oops.pycaught error: hello worldTo identify the exception with a class, I just changed the first part of the file tothis, and saved it as oop_oops.py:class MyError: passdef oops( ):raise MyError( )...rest unchanged...Like all class exceptions, the instance comes back as the extra data; the errormessage now shows both the class and its instance ().% python oop_oops.pycaught error: __main__.MyError 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 24 for details.3. Error handling. Here’s one way to solve this one (file safe2.py). I did my tests in afile, rather than interactively, but the results are about the same.import sys, tracebackdef safe(entry, *args):try:apply(entry, args)# Catch everything elseexcept:traceback.print_exc( )print 'Got', sys.exc_type, sys.exc_valuePart VII, Exceptions and Tools | 673

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!