15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

10.9. *Creating Exceptions<br />

Although the set of standard exceptions is fairly wide-ranging, it may be advantageous to create your<br />

own exceptions. One situation is where you would like additional information from what a standard or<br />

module-specific exception provides. We will present two examples, both related to IOError.<br />

IOError is a generic exception used for input/output problems, which may arise from invalid file access<br />

or other forms of communication. Suppose we wanted to be more specific in terms of identifying the<br />

source of the problem. For example, for file errors, we want to have a FileError exception that behaves<br />

like IOError, but with a name that has more meaning when performing file operations.<br />

Another exception we will look at is related to network programming with sockets. The exception<br />

generated by the socket module is called socket.error and is not a built-in exception. It is subclassed<br />

from the generic Exception exception. However, the exception arguments from socket.error closely<br />

resemble those of IOError exceptions, so we are going to define a new exception called NetworkError,<br />

which subclasses from IOError but contains at least the information provided by socket.error.<br />

Like classes and object-oriented programming, we have not formally covered network programming at<br />

this stage, but skip ahead to Chapter 16 if you need to.<br />

We now present a module called myexc.py with our newly customized exceptions FileError and<br />

NetworkError. The code is in Example 10.2.<br />

Example 10.2. Creating Exceptions (myexc.py)<br />

This module defines two new exceptions,FileError and NetworkError, as well as<br />

reimplements more diagnostic versions of open() [myopen()] and socket.connect()<br />

[myconnect()]. Also included is a test function [test()] that is run if this module is executed<br />

directly.<br />

1 #!/usr/bin/env python<br />

2<br />

3 import os, socket, errno, types, tempfile<br />

4<br />

5 class NetworkError(IOError):<br />

6 pass<br />

7<br />

8 class FileError(IOError):<br />

9 pass<br />

10<br />

11 def updArgs(args, newarg=None):<br />

12 if isinstance(args, IOError):<br />

13 myargs = []<br />

14 myargs.extend([arg for arg in args])<br />

15 else:<br />

16 myargs = list(args)<br />

17<br />

18 if newarg:<br />

19 myargs.append(newarg)<br />

20

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

Saved successfully!

Ooh no, something went wrong!