Exceptions in Python
Whenever exception occurs A “traceback” notice appears along with a notice with as much diagnostic information as the interpreter can give you, including the error name, reason, and perhaps even the line number near or exactly where the error occurred. All errors have a similar format, regardless of whether running within the Python interpreter or standard script execution, providing a consistent error interface. All errors, whether they be syntactical or logical, result from behavior incompatible with the Python interpreter and cause exceptions to be raised.
Let us take a look at some exceptions now.
NameError: attempt to access an undeclared variable.
NameError indicates access to an uninitialized variable. The offending identifier was not found in the Python interpreter’s symbol table.Accessing a variable entails a search by the interpreter, and if the name requested is not found in any of the namespaces, a NameError exception will be generated.
ZeroDivisionError:division by any numeric zero.
>>> 12.4/0.0 Traceback (innermost last): File "<interactive input>", line 0, in ? ZeroDivisionError: float division
Our example above used floats, but in general, any numeric division-by-zero will result in a ZeroDivisionError exception.
SyntaxError: Python interpreter syntax error
>>> for File "<string>", line 1 for ^ SyntaxError: invalid syntax
SyntaxError exceptions are the only ones which do not occur at run-time. They indicate an improperly constructed piece of Python code which cannot execute until corrected. These errors are generated at compile-time, when the interpreter loads and attempts to convert your script to Python bytecode. These may also occur as a result of importing a faulty module.
IndexError: request for an out-of-range index for sequence
>>> aList = [] >>> aList[0] Traceback (innermost last): File "<stdin>", line 1, in ? IndexError: list index out of range
IndexError is raised when attempting to access an index which is outside the valid range of a sequence.
KeyError: request for a non-existent dictionary key
>>> aDict = {'host': 'earth', 'port': 80} >>> print aDict['server'] Traceback (innermost last): File "<stdin>", line 1, in ? KeyError: server
Mapping types such as dictionaries depend on keys to access data values. Such values are not retrieved if an incorrect/nonexistent key is requested. In this case, a KeyError is raised to indicate such an incident has occurred.
IOError: input/output error
>>> f = open("blah") Traceback (innermost last): File "<interactive input>", line 1, in ? IOError: [Errno 2] No such file or directory: 'blah'
Attempting to open a non-existent disk file is one example of an operating system input/output (I/O) error. Any type of I/O error raises an IOError exception.