Feb. 16, 2011, 12:46 p.m.
posted by kudio
As we've already seen, Python comes with a number of base exceptions and exception classes. All of these can be used and trapped within your scripts to indicate or identify an error. If you are creating new exceptions then you should consider using one of these exceptions as the base class. See Fig 6.1 for an example of the class structure for the exception system.
This is the root class used for all exceptions. Note that a string operation on the arguments returned from any exception should give a string representation of the error that occurred, irrespective of the number or type of arguments supplied. To obtain the individual arguments of any exception use the data format of the except statement passing a tuple of names into which the information should be placed:
try: pow(2,262) except Exception,(args,): print args
Alternatively, if you fail to supply an explicit tuple of tuple, as in:
except Exception,args: print args
Then args will now hold the tuple of values returned by the exception.
The base class used for all the built-in exceptions, which also inherits the facilities offered by the Exception root class.
For exceptions arising due to arithmetic errors you will get one of the specific arithmetic exceptions, one of OverflowError, ZeroDivisionError, or FloatingPointError. This is the base class used by all three exceptions to indicate a general arithmetical fault. Since it's the base class, you can use this exception to trap all three specific arithmetic errors.
The exception raised when an assert statement fails.
The exception raised when an attribute reference or assignment fails. Note that if the type does not support attributes then a TypeError will be raised.
The class for errors that occur outside of Python's control, but that can be traced to the environment in which Python is operating. Used as the base class for IOError and OSError exceptions.
The standard arguments returned by the exception will be a two- or three-element tuple. In the two-element format the first element is the error number (errno) as returned by the operating system and the second element is the associated error string. In the three-element version, the third element will be the filename used when the exception was raised.
try: open('nosuchfile') except EnvironmentError,(errno,string): print "Whoops!: %s (%d)" % (string, errno)
The exception raised when the end-of-file (EOF) condition is detected by the built-in data handling functions. Note that this will only be raised if the EOF is raised without any data being read from the source. Also note that the built-in read and readline methods return an empty string on EOF.
Raised when a floating point operation fails – but only available if the interpreter has been compiled with floating point signal handling enabled. If not compiled with this option an ArithmeticError exception is raised instead.
The exception raised when an import statement fails to find the specified module, or when from fails to find the specific symbol in the module. See the section on Modules in Chapter 7, for more information on import methods and semantics.
The exception raised when you try to access a sequence element out of the range of the sequence's size. Note that a non-sequenced object will return TypeError if you try to access an element via the normal subscript notation.
The exception raised when an I/O operation fails, such as trying to open a non-existent file or writing to a device with no free space. The information supplied by the exception is the same as that given by any exception based on the EnvironmentError class.
The exception raised when the dictionary or other mapping key requested does not exist within the mapping object.
Raised when the interrupt key combination (Control-C or Command-. on the Mac) is pressed. The exception is raised even when the built-in input or raw_input functions have been called.
The base exception class for the built-in IndexError and KeyError exceptions used to indicate an error when accessing information from a sequence (string, list, tuple) or mapping (dictionary).
The exception raised when the interpreter runs out of memory whilst executing a specific statement, but one that the interpreter still thinks it can recover from the situation if some objects are deleted to free up memory. It may not always be possible to recover from the situation, but by raising an exception a traceback for the program will be triggered. The data passed by the exception will describe what kind of internal operation triggered the exception.
The exception raised when the object specified cannot be found within either the local or global scope. The data passed by the exception will indicate the name that failed.
The exception raised when an abstract user-defined error requires methods that can't be found. Derived from the RuntimeError exception.
The exception raised when an operating system error occurs – usually through the OS module interface. Derived from the EnvironmentError exception.
The exception raised when an arithmetical operation exceeds the limits of the Python interpreter. Note that when doing long integer math the interpreter will raise a MemoryError rather than an OverflowError.
The exception raised when there has been a runtime error that cannot be represented by one of the other exception types. This is included for compatibility only, since most errors now have their own exception class. The data passed by the exception will be a string indicating the error that occurred.
The exception raised when a syntax error occurs, either within the original script, during an import or exec statement or within the built-in eval function.
The information returned by the exception will be a simple string of the error message. If you are accessing the exception object directly then the object will include the attributes filename, lineno, the offset within the line and the actual text of the line.
For a more detailed analysis, the data passed by the exception can be accessed as a tuple of the form (message, (filename, lineno, offset, text)). For example, the code
try: eval("print :") except SyntaxError,(message,(filename,lineno, offset,text)): print "Error in line %d, from file %s: \n" % (lineno, filename),\text,"\n",\ ' ' * offset+"^", message
will generate the following output when executed:
Error in line 1, from file None: print : ^ invalid syntax
The exception raised when a system error occurs. This applies to internal Python errors that can be safely trapped and could potentially be recovered from. The data passed by the exception will be a string representing the error that went wrong.
Note that you should send SystemError exception information to the Python maintainers (see Appendix B) as it indicates a possible error with the interpreter.
The exception raised when the sys.exit() function is called. Normally the Python interpreter exits without any error or traceback being printed.
Raised when a built-in operation or function is applied to an object of inappropriate type. The returned value is a string giving details about the type mismatch.
The exception raised when a reference is made to a local variable (within the scope of a function or method) but no value has been bound to that variable.
The exception raised when a Unicode-related encoding or decoding error occurs.
The exception raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.
The exception raised when a Windows-specific error occurs. Also raised when the error number returned does not match a valid errno value. The actual values returned are populated using the GetLastError and FormatMessage Windows API calls.
The exception raised when the second argument of a division or modulo operation is zero. The returned value is a string indicating the type of the operands and the operation.