There are several built-in exceptions in Python that are raised when errors occur. These built-in exceptions can be viewed using the local() built-in functions as follows :
This returns a dictionary of built-in exceptions, functions and attributes.
The following exceptions are used mostly as base classes for other exceptions.
The following exceptions are the exceptions that are usually raised.
- exception AssertionError
An AssertionError is raised when an assert statement fails.Example :
assert False, 'The assertion failed'
Output :
Traceback (most recent call last):
File "exceptions_AssertionError.py", line 12, in
assert False, 'The assertion failed'
AssertionError: The assertion failed
- exception AttributeError
An AttributeError is raised when an attribute reference or assignment fails such as when a non-existent attribute is referenced.Example :
class Attributes( object ):
pass
object = Attributes()
print ( object .attribute)
|
Output :
Traceback (most recent call last):
File "d912bae549a2b42953bc62da114ae7a7.py", line 5, in
print object.attribute
AttributeError: 'Attributes' object has no attribute 'attribute'
- exception EOFError
An EOFError is raised when built-in functions like input() hits an end-of-file condition (EOF) without reading any data. The file methods like readline() return an empty string when they hit EOF.Example :
while True :
data = input ( 'Enter name : ' )
print ( 'Hello ' , data)
|
Output :
Enter Name :Hello Aditi
Enter Name :Traceback (most recent call last):
File "exceptions_EOFError.py", line 13, in
data = raw_input('Enter name :')
EOFError: EOF when reading a line
- exception FloatingPointError
A FloatingPointError is raised when a floating point operation fails. This exception is always defined, but can only be raised when Python is configured with the–with-fpectl option, or the WANT_SIGFPE_HANDLER symbol is defined in the pyconfig.h file.Example :
import math
print (math.exp( 1000 ))
|
Output :
Traceback (most recent call last):
File "", line 1, in
FloatingPointError: in math_1
- exception GeneratorExit
This exception directly inherits from BaseException instead of Exception since it is technically not an error. A GeneratorExit exception is raised when a generator or coroutine is closed.Example :
def my_generator():
try :
for i in range ( 5 ):
print ( 'Yielding' , i)
yield i
except GeneratorExit:
print ( 'Exiting early' )
g = my_generator()
print (g. next ())
g.close()
|
Output :
Yielding 0
0
Exiting early
- exception ImportError
An ImportError is raised when the import statement is unable to load a module or when the “from list” in from … import has a name that cannot be found.Example :
import module_does_not_exist
|
Output :
Traceback (most recent call last):
File "exceptions_ImportError_nomodule.py", line 12, in
import module_does_not_exist
ImportError: No module named module_does_not_exist
Example :
from exceptions import Userexception
|
Output :
Traceback (most recent call last):
File "exceptions_ImportError_missingname.py", line 12, in
from exceptions import Userexception
ImportError: cannot import name Userexception
- exception ModuleNotFoundError
This is the subclass of ImportError which is raised by import when a module could not be found. It is also raised when None is found in sys.modules. - exception IndexError
An IndexError is raised when a sequence is referenced which is out of range.Example :
array = [ 0 , 1 , 2 ]
print (array[ 3 ])
|
Output :
Traceback (most recent call last):
File "exceptions_IndexError.py", line 13, in
print array[3]
IndexError: list index out of range
- exception KeyError
A KeyError is raised when a mapping key is not found in the set of existing keys.Example :
array = { 'a' : 1 , 'b' : 2 }
print (array[ 'c' ])
|
Output :
Traceback (most recent call last):
File "exceptions_KeyError.py", line 13, in
print array['c']
KeyError: 'c'
- exception KeyboardInterrupt
This error is raised when the user hits the interrupt key such as Control-C or Delete.Example :
try :
print ( 'Press Return or Ctrl-C:' ,)
ignored = input ()
except Exception, err:
print ( 'Caught exception:' , err)
except KeyboardInterrupt, err:
print ( 'Caught KeyboardInterrupt' )
else :
print ( 'No exception' )
|
Output :
Press Return or Ctrl-C: ^CCaught KeyboardInterrupt
- exception MemoryError
This error is raised when an operation runs out of memory.Example :
def fact(a):
factors = []
for i in range ( 1 , a + 1 ):
if a % i = = 0 :
factors.append(i)
return factors
num = 600851475143
print (fact(num))
|
Output :
Traceback (most recent call last):
File "4af5c316c749aff128df20714536b8f3.py", line 9, in
print fact(num)
File "4af5c316c749aff128df20714536b8f3.py", line 3, in fact
for i in range(1, a+1):
MemoryError
- exception NameError
This error is raised when a local or global name is not found. For example, an unqualified variable name.Example :
def func():
print ans
func()
|
Output :
Traceback (most recent call last):
File "cfba0a5196b05397e0a23b1b5b8c7e19.py", line 4, in
func()
File "cfba0a5196b05397e0a23b1b5b8c7e19.py", line 2, in func
print ans
NameError: global name 'ans' is not defined
- exception NotImplementedError
This exception is derived from RuntimeError. Abstract methods in user defined classed should raise this exception when the derived classes override the method.Example :
class BaseClass( object ):
def __init__( self ):
super (BaseClass, self ).__init__()
def do_something( self ):
raise NotImplementedError( self .__class__.__name__ + '.do_something' )
class SubClass(BaseClass):
def do_something( self ):
print ( self .__class__.__name__ + ' doing something!' )
SubClass().do_something()
BaseClass().do_something()
|
Output :
Traceback (most recent call last):
File "b32fc445850cbc23cd2f081ba1c1d60b.py", line 16, in
BaseClass().do_something()
File "b32fc445850cbc23cd2f081ba1c1d60b.py", line 7, in do_something
raise NotImplementedError(self.__class__.__name__ + '.do_something')
NotImplementedError: BaseClass.do_something
- exception OSError([arg])
The OSError exception is raised when a system function returns a system-related error, including I/O failures such as “file not found” or “disk full” errors.Example :
def func():
print (ans)
func()
|
Output :
Traceback (most recent call last):
File "442eccd7535a2704adbe372cb731fc0f.py", line 4, in
print i, os.ttyname(i)
OSError: [Errno 25] Inappropriate ioctl for device
- exception OverflowError
The OverflowError is raised when the result of an arithmetic operation is out of range. Integers raise MemoryError instead of OverflowError. OverflowError is sometimes raised for integers that are outside a required range. Floating point operations are not checked because of the lack of standardization of floating point exception handling in C.Example :
import sys
print ( 'Regular integer: (maxint=%s)' % sys.maxint)
try :
i = sys.maxint * 3
print ( 'No overflow for ' , type (i), 'i =' , i)
except OverflowError, err:
print ( 'Overflowed at ' , i, err)
print ()
print ( 'Long integer:' )
for i in range ( 0 , 100 , 10 ):
print ( '%2d' % i, 2L * * i)
print ()
print ( 'Floating point values:' )
try :
f = 2.0 * * i
for i in range ( 100 ):
print (i, f)
f = f * * 2
except OverflowError, err:
print ( 'Overflowed after ' , f, err)
|
Output :
Regular integer: (maxint=9223372036854775807)
No overflow for i = 27670116110564327421
Long integer:
0 1
10 1024
20 1048576
30 1073741824
40 1099511627776
50 1125899906842624
60 1152921504606846976
70 1180591620717411303424
80 1208925819614629174706176
90 1237940039285380274899124224
Floating point values:
0 1.23794003929e+27
1 1.53249554087e+54
2 2.34854258277e+108
3 5.5156522631e+216
Overflowed after 5.5156522631e+216 (34, 'Numerical result out of range')
- exception RecursionError
The RecursionError is derived from the RuntimeError. This exception is raised when the interpreter detects that the maximum recursion depth is exceeded. - exception ReferenceError
The ReferenceError is raised when a weak reference proxy is used to access an attribute of the referent after the garbage collection.Example :
import gc
import weakref
class Foo( object ):
def __init__( self , name):
self .name = name
def __del__( self ):
print ( '(Deleting %s)' % self )
obj = Foo( 'obj' )
p = weakref.proxy(obj)
print ( 'BEFORE:' , p.name)
obj = None
print ( 'AFTER:' , p.name)
|
Output :
BEFORE: obj
(Deleting )
AFTER:
Traceback (most recent call last):
File "49d0c29d8fe607b862c02f4e1cb6c756.py", line 17, in
print 'AFTER:', p.name
ReferenceError: weakly-referenced object no longer exists
- exception RuntimeError
The RuntimeError is raised when no other exception applies. It returns a string indicating what precisely went wrong. - exception StopIteration
The StopIteration error is raised by built-in function next() and an iterator‘s __next__() method to signal that all items are produced by the iterator.Example :
Arr = [ 3 , 1 , 2 ]
i = iter (Arr)
print (i)
print (i. next ())
print (i. next ())
print (i. next ())
print (i. next ())
|
Output :
3
1
2
Traceback (most recent call last):
File "2136fa9a620e14f8436bb60d5395cc5b.py", line 8, in
print i.next()
StopIteration
- exception SyntaxError
The SyntaxError is raised when the parser encounters a syntax error. A syntax error may occur in an import statement or while calling the built-in functions exec() or eval(), or when reading the initial script or standard input.Example :
try :
print ( eval ( 'geeks for geeks' ))
except SyntaxError, err:
print ( 'Syntax error %s (%s-%s): %s' % \
(err.filename, err.lineno, err.offset, err.text))
print (err)
|
Output :
Syntax error (1-9): geeks for geeks
invalid syntax (, line 1)
- exception SystemError
The SystemError is raised when the interpreter finds an internal error. The associated value is a string indicating what went wrong. - exception SystemExit
The SystemExit is raised when sys.exit() function is called. A call to sys.exit() is translated into an exception to execute clean-up handlers (finally clauses of try statements) and to debug a script without running the risk of losing control. - exception TypeError
TypeError is raised when an operation or function is applied to an object of inappropriate type. This exception returns a string giving details about the type mismatch.Example :
arr = ( 'tuple' , ) + 'string'
print (arr)
|
Output :
Traceback (most recent call last):
File "30238c120c0868eba7e13a06c0b1b1e4.py", line 1, in
arr = ('tuple', ) + 'string'
TypeError: can only concatenate tuple (not "str") to tuple
- exception UnboundLocalError
UnboundLocalError is a subclass of NameError which is raised when a reference is made to a local variable in a function or method, but no value has been assigned to that variable.Example :
def global_name_error():
print (unknown_global_name)
def unbound_local():
local_val = local_val + 1
print (local_val)
try :
global_name_error()
except NameError, err:
print ( 'Global name error:' , err)
try :
unbound_local()
except UnboundLocalError, err:
print ( 'Local name error:' , err)
|
Output :
Global name error: global name 'unknown_global_name' is not defined
Local name error: local variable 'local_val' referenced before assignment
- exception UnicodeError
This exception is a subclass of ValueError. UnicodeError is raised when a Unicode-related encoding or decoding error occurs. - exception ValueError
A ValueError is raised when a built-in operation or function receives an argument that has the right type but an invalid value.Example :
Output :
Traceback (most recent call last):
File "44f00efda935715a3c5468d899080381.py", line 1, in
print int('a')
ValueError: invalid literal for int() with base 10: 'a'
- exception ZeroDivisionError
A ZeroDivisionError is raised when the second argument of a division or modulo operation is zero. This exception returns a string indicating the type of the operands and the operation.Example :
Output :
Traceback (most recent call last):
File "c31d9626b41e53d170a78eac7d98cb85.py", line 1, in
print 1/0
ZeroDivisionError: integer division or modulo by zero
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.