The exceptions Module

The exceptions module provides the standard exception hierarchy. It's automatically imported when Python starts, and the exceptions are added to the _ _builtin_ _ module. In other words, you usually don't need to import this module.

This is a Python module in 1.5.2, and a built-in module in 2.0 and later.

The following standard exceptions are defined by this module:

You can create your own exception classes. Just inherit from the built-in Exception class (or a proper standard exception), and override the constructor and/or _ _str_ _ method as necessary. Example 1-26 shows the exceptions module.

Example 1-26. Using the exceptions Module

File: exceptions-example-1.py # python imports this module by itself, so the following # line isn't really needed # import exceptions class HTTPError(Exception): # indicates an HTTP protocol error def _ _init_ _(self, url, errcode, errmsg): self.url = url self.errcode = errcode self.errmsg = errmsg def _ _str_ _(self): return ( "" % (self.url, self.errcode, self.errmsg) ) try: raise HTTPError("http://www.python.org/foo", 200, "Not Found") except HTTPError, error: print "url", "=>", error.url print "errcode", "=>", error.errcode print "errmsg", "=>", error.errmsg raise # reraise exception url => http://www.python.org/foo errcode => 200 errmsg => Not Found Traceback (innermost last): File "exceptions-example-1", line 16, in ? HTTPError:

Категории