Python Exception Classes
There are several exceptions available as part of Python language that are called built-in exceptions. In the same way, the programmer can also create his own exceptions called user-defined exceptions.
This Table summarizes some important built-in exceptions in Python. Most of the exception class names end with the word 'Error'.
Python Built-in Exceptions
Exception Class Name | Description |
---|---|
Exception | Represents any type of exception. All exceptions are sub classes of this class. |
ArithmeticError | Represents the base class for arithmetic errors like OverflowError,ZeroDivisionError,FloatingPointError. |
AssertionError | Raised when an assert statement gives error. |
AttributeError | Raised when an attribute reference or assignment fails. |
EOFError | Raised when input() function reaches end of file condition without reading any data. |
FloatingPointError | Raised when a floating point operation fails. |
GeneratorExit | Raised when generator's close() method is called. |
IOError | Raised when an input or output operation failed. It raises when the file opened is not found or when writing data disk is full. |
ImportError | Raised when an import statement fails to find the module being imported. |
IndexError | Raised when a sequence index or subscript is out of range. |
KeyError | Raised when a mapping (dictionary) key is not found in the set of existing keys. |
KeyboardInterrupt | Raised when the user hits the interrupt key(normally control-C or Delete). |
NameError | Raised when an identifier is not found locally or globally. |
NotImplementedError | Derived from 'RuntimeError'. In user defined base classes,abstract methods should raise this exception when they require derived classes to override the method. |
OverflowError | Raised when the result of an arithmetic operation is to large too be represented. This cannot occur for long integers (which would rather raise 'MemoryError'). |
RuntimeError | Raised when an error is detected that doesn't fall in any of the other categories. |
StopIteration | Raised by an iterator's next() method to signal that there are no more elements. |
SyntaxError | Raised when the compiler encounters a syntax error.Import or exec statements and input() and eval() functions may raise this exception. |
IndentationError | Raised when indentation is not specified properly. |
SystemExit | Raised by the sys.exit() function. When it is not handled, the Python interpreter exits. |
TypeError | Raised when an operation or function is applied to an object of inappropriate datatype. |
UnboundLocalError | Raised when a reference is made to a local variable in a function or method, but no value has been bound to that variable. |
ValueError | Raised when a built-in operation or function receives an argument that has right datatype but wrong value. |
ZeroDivisionError | Raised when the denominator is zero in adivision or modulus operation. |
SyntaxError exception class
Copied
#example for syntax error
try:
date = eval(input("Enter date:"))
except SyntaxError:
print('Invalid date entered')
else:
print('You entered:', date)
A Python program to handle IOError produced by open() function.
#example for IOError #accept a filename
try:
name = input('Enter filename:')
f = open(name, 'r')
except IOError:
print('File not found:', name)
else:
n = len(f.readlines())
print(name, 'has', n, 'lines')
f.close()
Handle Multiple Exception classes
Copied
#a function to find total and average of list elements
def avg(list):
tot=0
for x in list:
tot+=x
avg = tot/len(list)
return tot, avg
#call the avg() and pass a list
try:
t,a = avg([1,2,3,4,5,'a'])
#here, give empty list and try.
print('Total= {}, Average= {}'.format(t,a))
except TypeError:
print('Type Error, please provide numbers.')
except ZeroDivisionError:
print('ZeroDivisionError, please do not give empty list.')