Open In App

Built-in Exceptions in Python

Improve
Improve
Like Article
Like
Save
Share
Report

All instances in Python must be instances of a class that derives from BaseException. Two exception classes that are not related via subclassing are never equivalent, even if they have the same name. The built-in exceptions can be generated by the interpreter or built-in functions.

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 :

>>> locals()['__builtins__']

This returns a dictionary of built-in exceptions, functions and attributes.

Base Classes

The following exceptions are used mostly as base classes for other exceptions.

  1. exception BaseException
    This is the base class for all built-in exceptions. It is not meant to be directly inherited by user-defined classes. For, user-defined classes, Exception is used. This class is responsible for creating a string representation of the exception using str() using the arguments passed. An empty string is returned if there are no arguments.

    • args : The args are the tuple of arguments given to the exception constructor.
    • with_traceback(tb) : This method is usually used in exception handling. This method sets tb as the new traceback for the exception and returns the exception object.

      Code :

      try:
          ...
      except SomeException:
          tb = sys.exc_info()[2]
          raise OtherException(...).with_traceback(tb)
      
  2. exception Exception
    This is the base class for all built-in non-system-exiting exceptions. All user-defined exceptions should also be derived from this class.
  3. exception ArithmeticError
    This class is the base class for those built-in exceptions that are raised for various arithmetic errors such as :

    • OverflowError
    • ZeroDivisionError
    • FloatingPointError

    Example :




    try:  
        a = 10/0  
        print (a)
    except ArithmeticError:  
            print ("This statement is raising an arithmetic exception.")
    else:  
        print ("Success.")

    
    

    Output :

    This statement is raising an arithmetic exception.
    
  4. exception BufferError
    This exception is raised when buffer related operations cannot be performed.
  5. exception LookupError
    This is the base class for those exceptions that are raised when a key or index used on a mapping or sequence is invalid or not found. The exceptions raised are :

    • KeyError
    • IndexError

    Example :




    try: 
        a = [1, 2, 3] 
        print (a[3]) 
    except LookupError: 
        print ("Index out of bound error.")
    else: 
        print ("Success")
      

    
    

    Output :

    Index out of bound error.
    

Concrete exceptions

The following exceptions are the exceptions that are usually raised.

  1. 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
    
  2. 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'
    
  3. 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
    
  4. 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
    
  5. 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
    
  6. 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
      
      
  7. 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.

  8. 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
    
  9. 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'
    
  10. 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
    
  11. 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
    
  12. 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
    
  13. 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):
        """Defines the interface"""
        def __init__(self):
            super(BaseClass, self).__init__()
        def do_something(self):
            """The interface, not implemented"""
            raise NotImplementedError(self.__class__.__name__ + '.do_something')
      
    class SubClass(BaseClass):
        """Implements the interface"""
        def do_something(self):
            """really does something"""
            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
    
  14. 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
    
  15. 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)