Concrete Exceptions in Python

PythonProgrammingServer Side Programming

There are some common exceptions in python. These exceptions are usually raised in different programs. These may raise by the programmer explicitly, or the python interpreter can raise these type of exceptions implicitly. Some of these exceptions are −

Exception AssertionError

The AssertionError may raise, when an assert statement fails. In python there are some, we can also set some assert statement in our code. The assert statement always must be true. if the condition fails, it will raise AssertionError.

Example Code

class MyClass:
   def __init__(self, x):
      self.x = x
      assert self.x > 50
 myObj = MyClass(5)

Output

---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-21-71785acdf821> in <module>()
      4         assert self.x > 50
      5 
----> 6 myObj = MyClass(5)

<ipython-input-21-71785acdf821> in __init__(self, x)
      2     def __init__(self, x):
      3         self.x = x
----> 4         assert self.x > 50
      5 
      6 myObj = MyClass(5)

AssertionError:

Exception AttributeError

The attribute error may raise, when we will try to access some attribute of a class, but it is not present in it.

Example Code

class point:
   def __init__(self, x=0, y=0):
      self.x = x
      self.y = y
        
   def getpoint(self):
      print('x= ' + str(self.x))
      print('y= ' + str(self.y))
      print('z= ' + str(self.z))
pt = point(10, 20)
pt.getpoint()

Output

x= 10
y= 20
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-15-f64eb52b2192> in <module>()
     10 
     11 pt = point(10, 20)
---> 12 pt.getpoint()

<ipython-input-15-f64eb52b2192> in getpoint(self)
      7         print('x= ' + str(self.x))
      8         print('y= ' + str(self.y))
----> 9         print('z= ' + str(self.z))
     10 
     11 pt = point(10, 20)

AttributeError: 'point' object has no attribute 'z'

Exception ImportError

The ImportError may occur when the import statement is facing some problem to import some module. It can also be raised, when the package name to a from statement is correct, but there is no module found as specified name.

Example Code

from math import abcd    def __init__(self, x=0, y=0):

Output

---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-23-ff4519a07c77> in <module>()
----> 1 from math import abcd

ImportError: cannot import name 'abcd'

Exception ModuleNotFoundError

It is a subclass of the ImportError. When a module is not located, this error may raise. It can also be raised when None is found in sys.modules.

Example Code

import abcd

Output

---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-24-7b45aaa048eb> in <module>()
----> 1 import abcd

ModuleNotFoundError: No module named 'abcd'

Exception IndexError

The index error may raise when the subscript of a sequence (List, Tuple, Set etc) is out of range.

Example Code

myList = [10, 20, 30, 40]
print(str(myList[5]))

Output

---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-29-a86bd85b04c9> in <module>()
      1 myList = [10, 20, 30, 40]
----> 2 print(str(myList[5]))

IndexError: list index out of range

Exception RecursionError

The RecursionError is a runtime error. When the maximum recursion depth is exceeded, then it will raised.

Example Code

def myFunction():
   myFunction()
myFunction()

Output

---------------------------------------------------------------------------
RecursionError Traceback (most recent call last)
<ipython-input-39-8a59e0fb982f> in <module>()
      2     myFunction()
      3 
----> 4 myFunction()

<ipython-input-39-8a59e0fb982f> in myFunction()
      1 def myFunction():
----> 2     myFunction()
      3 
      4 myFunction()

... last 1 frames repeated, from the frame below ...

<ipython-input-39-8a59e0fb982f> in myFunction()
      1 def myFunction():
----> 2     myFunction()
      3 
      4 myFunction()

RecursionError: maximum recursion depth exceeded

Exception StopIteration

In python, we can get the StopIteration error by the inbuilt method called next(). When one iterator has no further element, then the next() method will raise the StopIteration error.

Example Code

myList = [10, 20, 30, 40]
myIter = iter(myList)
while True:
   print(next(myIter))

Output

10
20
30
40
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-42-e608e2162645> in <module>()
      2 myIter = iter(myList)
      3 while True:
----> 4     print(next(myIter))

StopIteration: 

Exception IndentationError

When there are some invalid indentation in the python code, it will raise this kind of errors. It inherits the SyntaxError class of python.

Example Code

for i in range(10):
   print("The value of i: " + str(i))

Output

File "<ipython-input-44-d436d50bbdc8>", line 2
    print("The value of i: " + str(i))
        ^
IndentationError: expected an indented block

Exception TypeError

The TypeError may occur when an operation is performed on an object of inappropriate type. For example, if we provide a floating point number in array index, it will return a TypeError.

Example Code

muList = [10, 20, 30, 40]
print(myList[1.25])

Output

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-46-e0a2a05cd4d4> in <module>()
      1 muList = [10, 20, 30, 40]
----> 2 print(myList[1.25])

TypeError: list indices must be integers or slices, not float

Exception ZeroDivisionError

When there is a situation where the denominator is 0 (zero) for a division problem, it will raise ZeroDivisionError.

Example Code

print(5/0)

Output

---------------------------------------------------------------------------
ZeroDivisionError  Traceback (most recent call last)
<ipython-input-48-fad870a50e27> in <module>()
----> 1 print(5/0)

ZeroDivisionError: division by zero
raja
Published on 30-Oct-2018 13:18:47
Advertisements