Python built-in exceptions

Counters | File handling | Python Methods and Functions

Python has several built-in exceptions that are thrown when errors are encountered. These built-in exceptions can be viewed using the built-in local () functions as follows:

 & gt; & gt; & gt; locals () [`__builtins__`] 

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

Base Classes

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

  1. BaseException
    This is the base class for all built-in exceptions. It is not intended to be directly inherited by user-defined classes. For custom classes, Exception is used. This class is responsible for creating a string representation of the exception using str () using the passed arguments. An empty string is returned if there are no arguments.
    • args: args — this is a set of arguments given to the exception constructor.
    • with_traceback (tb): This method is typically used when handling exceptions. This method sets tb as the new trace for the exception and returns an 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 outputs. All user-defined exceptions must also derive from this class.
  3. ArithmeticError
    This class is the base class for those built-in exceptions that are thrown by various arithmetic errors such like:
    • OverflowError
    • ZeroDivisionError
    • FloatingPointError

    Example:

    try

      a = 10 / 0  

    print

    except ArithmeticError: 

    print "This statement is raising an arithmetic exception."  

    else

    print "Success."

    Output:

     This statement is raising an arithmetic exception. 
  4. BufferError exception
    This exception is thrown when buffer operations cannot be performed.
  5. LookupError exception
    This is the base class for those exceptions that are thrown when a key or index used in a display or sequence is invalid or not found. Exceptions are thrown:
    • 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. 

Specific exceptions

The following exceptions — these are the exceptions that usually occur.

  1. AssertionError
    An AssertionError is thrown when the assert statement fails.

    Example:

     assert False, `The assertion failed` 

    Exit:

     Traceback (most recent call last): File" exceptions_AssertionError. py ", line 12, in assert False,` The assertion failed` AssertionError: The assertion failed 
  2. AttributeError
    attribute or assignments, such as when referring to a nonexistent attribute.

    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. EOFError exception
    An EOFEr error occurs when built-in functions such as input () reach an end-of-file (EOF) condition without reading any data. File methods such as readline () return an empty line when they reach EOF.

    Example:

    while True :

    data = raw_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. FloatingPointError
    A FloatingPointError is thrown when a floating point operation fails. This exception is always detected, but can only be thrown if 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. GeneratorExit
    This exception directly inherits from BaseException instead of Exception, since it is not technically an error. GeneratorExit is thrown 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 ()

     

    Exit:

     Yielding 0 0 Exiting early 
  6. ImportError
    An ImportError is thrown when a module cannot be loaded in an import statement, or when "from the 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 a subclass of ImportError that is called on import when the module cannot be found. It is also called when there is no None in sys.modules.
  8. IndexError
    IndexError is thrown when a link is referenced that 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. KeyError exception 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. KeyboardInterrupt exception
    This error occurs when the user clicks t break key, such as Control-C or Delete.

    Example:

    try :

    print `Press Return or Ctrl-C:` ,

    ignored = raw_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. MemoryError exception
    This error occurs when an operation is 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 )

    B 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. NameError exception
    This error occurs when no local or global name was 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 ` is not defined  strong> NotImplementedError exception  
    This exception comes from RuntimeError. Abstract methods in a user-defined classification should throw this exception when derived classes override the method.

    Example:

    class BaseClass ( object ):

    & quot; & quot; & quot; Defines an interface & quot; & quot; & quot;

    def __ init__ ( self ):

    super (BaseClass, self ) .__ init __ ()

    def do_something ( self ):

    & quot; & quot; & quot; Interface, not implemented & quot; & quot; & quot;

    raise NotImplementedError ( self .__ class __.__ name__ + `.do_something` )

      

    class SubClass (BaseClass):

    & quot; & quot; & quot; Implements interface & quot; & quot; & quot;

    def do_something ( self ):

    & quot; & quot; `` really does something `` & quot; & quot;

    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 "b32fc445850cbc23cd2f081ba1c" 7, in do_something raise NotImplementedError (self .__ class __.__ name__ + `.do_something`) NotImplementedError: BaseClass.do_something 
  13. OSError exception ([arg])
    An OSError exception is thrown when a system function returns a system error, including I / O errors such as " file not found "or" disk full. "

    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 
  14. OverflowError exception
    An OverflowError occurs when the result of an arithmetic operation is out of range. Integers raise MemoryError instead of OverflowError. An OverflowError is sometimes thrown for integers that are outside the required range. Floating point operations are not checked due to 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` , ty pe (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

    Exit:

     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 70119246 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`) 
  15. RecursionError
    RecursionError derives from RuntimeError. This exception is thrown when the interpreter detects that the maximum recursion depth has been exceeded.
  16. ReferenceError
    A ReferenceError is thrown when a weak reference proxy is used to access the referent attribute after 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 
  17. RuntimeError
    A RuntimeError is thrown when no other exception applies. Returns a string indicating exactly what went wrong.
  18. exception
    The StopIteration error is raised by the built-in next () function and the __next __ () method of the iterator to signal that all elements are created by an iterator.

    Example:

    Arr = [ 3 , 1 , 2 ]

    i = iter (Arr )

     

    print i

    print i. next ()

    print i. next ()

    print i. next ()

    <



    Get Solution for free from DataCamp guru