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.

except StandardError:...handle <strong>Python</strong> errors...except:...handle user exceptions...else:...handle no-exception case...You can also almost simulate an empty except clause (that catches everything) bycatching the root class Exception. This doesn’t quite work, however, because it won’tcatch string exceptions, and standalone user-defined exceptions are not currentlyrequired to be subclasses of the Exception root class.Whether or not you will use categories in the built-in class tree, it serves as a goodexample; by using similar techniques for class exceptions in your own code, you canprovide exception sets that are flexible and easily modified.Other than in the respects that we have covered here, built-in exceptions are largelyindistinguishable from the original string-based model. In fact, you normally don’tneed to care that they are classes unless you assume built-in exceptions are strings andtry to concatenate without converting (e.g., KeyError + "spam" fails, but str(KeyError)+ "spam" works).Specifying Exception TextWhen we met string-based exceptions at the start of this chapter, we saw that thetext of the string shows up in the standard error message when the exception is notcaught (i.e., when it’s propagated up to the top-level default exception handler). Butwhat does this message contain for an uncaught class exception? By default, you getthe class’ name, and a not very pretty display of the instance object that was raised:>>> class MyBad: pass>>> raise MyBad( )Traceback (most recent call last):File "", line 1, in raise MyBad( )MyBad: To improve this display, define either the _ _repr_ _ or _ _str_ _ string-representationoverloading method in your class to return the string you want to display for yourexception if it reaches the default handler:>>> class MyBad:... def _ _repr_ _(self):... return "Sorry--my mistake!"...>>> raise MyBad( )Traceback (most recent call last):File "", line 1, in raise MyBad( )MyBad: Sorry--my mistake!610 | Chapter 28: Exception Objects

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

Saved successfully!

Ooh no, something went wrong!