As you’ve already seen, Python comes with a number of base exceptions and exception classes. All of these exceptions can be used and trapped within your scripts to indicate or identify an error. If you are creating new exceptions (described in “Rolling Your Own Exceptions” later in this chapter), consider using one of these exceptions as the base class. See Figure 7-1 for an illustration 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 now holds the tuple of values returned by the exception.
StandardError is the base class used for all the built-in exceptions. StandardError inherits the facilities offered by the Exception root class.
For exceptions arising due to arithmetic errors, one of the specific arithmetic exceptions (OverflowError, ZeroDivisionError, or FloatingPointError) is raised. ArithmeticError 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.
AssertionError is the exception raised when an assert statement fails.
AttributeError is the exception raised when an attribute reference or assignment fails. Note that if the object type does not support attributes then a TypeError is raised.
EnvironmentError is 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 EnvironmentError as the base class for IOError and OSError exceptions.
The standard arguments returned by this exception are 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 is the filename used when the exception was raised.
try: open('nosuchfile') except EnvironmentError, (errno,string): print "Whoops: %s (%d)" % (string, errno)
EOFError is the exception raised when the end-of-file feof) condition is detected by the built-in data-handling functions. Note that this exception is only raised if the cof is detected without any data being read from the source. Note also that the built-in read and readline methods return an empty string when the eof is detected.
The Floating PointError exception is raised when a floating-point operation fails. This exception is only available in the interpreter has been compiled with floating-point signal handling enabled. If not compiled with this option, an Arithmetic Error exception is raised instead.
The ImportError exception in raised when an import statement fails to find the specified module or when from fails to find the specific symbol in the module, See Chapter 5 for more information on import methods and semantics.
The IndexError exception is raised when you try to access a sequence element out of the range of the sequence’s size. Note that a nonsequenced object returns TypeError if you try to access an element via the normal subscript notation.
The IOError exception is raised when an I/O operation fails, for example, trying to open a nonexistent file or trying to write to a device with no free space. The information supplied by the exception is the same as the information supplied by any exception based on the EnvironmentError class.
The KeyError exception is raised when the dictionary or other mapping key requested does not exist within the mapping object.
The KeyboardInterrupt exception is raised when the interrupt key combination (Ctrl-C on a PC or Command on a Mac) is pressed. This exception is raised even when the built-in input or raw input functions have been called.
LankupError is the base exception class for the built-in IndexError and KeyError exceptions. This exception is used to indicate an error when accessing information frits a sequence (string, list, or tuple) or mapping (dictionary).
The MemoryError exception is raised when the interpreter runs out of memory while executing a specific option, but 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 this situation, but by raising an exception, a stack trace for the program is triggered The data passed by the exception describes what kind of internal operation triggered the exception (although it may not always be possible).
The NameError excepnon is raised when the object specified cannot be found within either the Incal or global scope. The data pasied by the exception indicates the name that failed.
The NotImplemented Error exception is raised when an abstract, user-defined error requires methods that can’t be found. This exception is derived from the RuntimeError exception.
The OfError exception is raised when an operating system error occurs, usually through the os module interface. This exception is derived from the EnvironmentError exception.
The OverflowError exception is raised when an arithmatical operation exceeds the limits of the Python interpretier. Note that when doing long-integer math, the interpreter raises a Memory Error ind of an OverflowError.
The RuntimeError exception is raised when there has been a run-time error that cannot be represented by one of the other exception types. This exception is included for compatibility only, since most errors nowe have their own exception class. The data passed by this exception is a string indicating the error that occurred.
The SyntaxError exception is 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 SyntaxError exception is a simple string of the error message. If you are accessing the exception object directly, the object includes the in 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 SyntaxError 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 : \n"% (lineno, filename),\ text, "in",\ ' ' * offset+"^", message
generates the following output when executed:
Error in line 1, from file None: print: ^Invalid syntax
The SystemError exception is raised when a system error occurs. Note that this exception applies to internal Python errors that can be safely trapped and could, potentially, be recovered from. The data passed by the SystemError exception is a string representing the error that went wrong.
Note:- You should send SystemError exception information to the Python maintainers (see Appendix B) because it indicates a possible error in the interpreter.
The SystemExit exception is raised when the sys.exit() function is called Normally, the Python interpreter exits without any error or stack trace being printed.
The TypeError exception is raised when a built-in operation or function is applied to an object of inappropriate type. The returned value is a string that gives details about the type mismatch.
The Unbound LocalError exception is raised when a reference is made to a local variable within the scope of a function or method, but no value as been bound to that variable.
The UnicodeError exception is raised when a Unicode-related encoding or decoding error occurs.
The ValueError exception is 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 WindowsError exception is raised when a Windows-specific error occurs. This exception is also raised when the error number returned does not match a valid ermo value. The actual values returned are populated using the GetLastError and FormatMessage Windows API calls.
The ZeroDivision Error exception is raised when the second argument of a division or modulo operation is 0. The returned value is a string that indicates the type of the operands and the operation.
Also Read:- Rolling Your Own Exceptions in python