Exceptions


Like C++ and Java, Python supports exception handling. For example, if you attempt to open a file that does not exist, or a file you do not have permission to read, Python will raise an IOError. You can handle this in your code. For example,

 try :     filein = open (inputfile, 'r') except IOError :     sys.stderr.write( "Error: cannot open %s\n" % inputfile)     sys.stderr.write( "%s: %s\n" % (sys.exc_type, sys.exc_value))     sys.exit(2)

In this example, Python will try to open inputfile. If it successfully opens the file, execution will continue after the try/except block. If it cannot open the file, however, Python will throw an IOError exception. The except statement catches the exception, and executes a block of code to handle it. The variable sys.exc_type gives the type of exception (although in this case, we already know that it was an IOError). The variable sys.exc_value has an error message generated by Python that may help to determine what went wrong. Finally, sys.exit() causes the script to terminate. In this example, sys.exit(2) returns the exit code 2 to indicate that there was error.

Because Python automatically generates detailed error messages, exception handling isn’t always necessary. Chapter 25 has a detailed description of how exception handling works in Java, which may be helpful if you want to learn more about exceptions. In addition, the books in the section “How to Find Out More” at the end of this chapter have more complete coverage of exception handling in Python.




UNIX. The Complete Reference
UNIX: The Complete Reference, Second Edition (Complete Reference Series)
ISBN: 0072263369
EAN: 2147483647
Year: 2006
Pages: 316

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net