Python Exception Handling

First of all, lets understand the difference between an error and an exception.

Error – It occurs because of syntactical error in a program.

Lets have a look when trying to use assignment operator instead of comparison operator, Below
error comes up.

if(i = 0 ):
    print("You are right")
else:
    print("You are wrong")
    

Output: See, it causes invalid Syntax error.

File "<ipython-input-156-19ff24171ea8>", line 1
    if(i = 0 ):
         ^
SyntaxError: invalid syntax

Visit the links to understand if statements in detail.
https://effortlesspython.com/python-conditional-statement-if-else-elif/

Exception Handling

Exception occurs when there is not syntax error in a code but code resulted in an error, which does not halt the program but it changes the flow of program.

In Example below – The Exception occurs divide by zero error infinite.

i = 5
div = i/0
print(div)

Output :
The program here shows the exception raised. Exception class is the base class of all the exceptions in python.

ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-157-bbfa82a53fe7> in <module>
      1 i = 5
----> 2 div = i/0
      3 print(div)

ZeroDivisionError: division by zero

Python try and except Block:

The exception occurs when we try to print the elements in the list which doesn’t exist

Lists = (1, 2, 3)
try:  
    print("Display 3 element", Lists[2]) 
  
    # There are 3 element in the List- results in error
    print("Display 4 element ", Lists[4])  
  
except IndexError: 
    print("Out of Bound error occurred")

Output

Display 3 element 3
Out of Bound error occurred

Leave a Comment