In Python, if program is syntactically correct but results in error generally is exception error like dividing by zero will leads to exception error. We have built in exception error and we can also raise the error using “raise exception”. We use try and except block to raise error. Try block contains the part to be executed. If it is having some error like undefined variable then exception block will throw an error. We will see the error handling with examples -:

Checking error using exception

In [1]:
## It is simply generating error with tracebacks
## Dividing by zero is undefined.

print(10/0)
Generating a traceback:
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-1-19547e02be0f> in <module>()
      2 ## Dividing by zero is undefined.
      3 
----> 4 print(10/0)

ZeroDivisionError: division by zero

Using try and except block

In [2]:
## Using try and except block trying the above code of diving by zero.
try:    a = 10/0

## It is simply generating an error in one line.
except Exception as e:
    print(str(e))
division by zero

How to raise custom exception.

Suppose we are writing one usable program and in that i want that variable not to be of int data type. So, by taking that example only we are raising the exception.In [3]:
## Setting the variable to integer value in order to generate exception.
a= 7

if str(type(a)) == "<class 'int'>":
    raise Exception('This variable cannot be integer')
-------------------------------------------------------------------------Exception: This variable cannot be integer
Hope this gives you idea how to check the error and handle it using try and exception block. Stay tuned! Keep learning with us. Enjoy learning Python.