Exception handling in Python

Exception or Error

There can be 2 type of error – Syntax Error or Exceptions.

Synax error encounters if you do not follow language syntax guidelines. common scenarios to face such errors are:

  1. you do not follow proper indentation.
if a= 0 print(a) else print('NA')

2. Suppose you have a method which takes 2 arguments and while calling it, you are providing only one argument.

def return_sum(a,b):
    return a+ b

val = return_sum(3)

There are multiple scenarios like this. In short, a syntax error occurs if the python interpreter fails to parse your code. Now let us discuss exception.

Exceptions are any unwanted thing which may interrupt the control flow of program.

Common Exceptions which you may face with python are – Name Error, Type Error, Runtime Error, or when you are working with files. In short, we can call exception as error faced while coding execution.

a = 10
b = a/0
 #Division by 0 Error
print("Var"+ 1) #Type Error 
print(c) #Name Error
with open('filedoesnotexist') as f: #OSError
    f.read()

your code will break as the exception encounters. Here you can see that control flow of the program is stopped because of ZeroDivisionError and that’s why the code below that statement never gets executed.

Exception Handling

To solve these scenarios we need to perform exception handling. If I am asked to give a crisp description of these keywords, I will say something like this.

put your IO method or DB related methods in a try block in which you think exception may occur. If an exception occurs, Handle it in Except block. If there is no exception, Put it in the else block. And if you want to run some methods whether exceptions are encountered or not, put it in finally block like cleaning up activity, closing the DB connections or releasing the resources.

There are 4 Keyword for Exception handling in python.

  • Try: Run this code
  • Except – Run this code if Exception occurs
  • Else – Run this code if Exception does not occur
  • Finally – Run this code always whether an Exception occurs or not.

Let us consider you want to write a program to get the value of a variable from a file and then delete it. If the file does not exist then you reset the value to 0 in the file.

import os
val=None
try:
    with open('filedoesnotexist.txt') as f:
        val = f.read()
except Exception as identifier:
    val=0
    with open('filedoesnotexist.txt','w') as f:
        f.write(str(val))
else:
    os.remove('filedoesnotexist.txt')
    print("Exception did not occured. Good Job")
finally:
    print(val)
    

To avoid the Name Error i have created val variable globally as it is being used in try, except and finally block. There is Input output operation so i have put the logic to read filedoesnotexist.txt in try block. If the file does not exist, we are resting the value of val to 0 and writing it to filedoesnotexist.txt. And if the file exists then we will not get any error so i am deleting that file and finally printing the value of val variable.

I Hope you got the basic idea of Exception handling. In the next post, I will tell you how to raise custom exception, create user defined Exception and how to debug the stack trace.

5 3 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x