Exception Handling in python

In this post,you will learn error and exception handling in python.You will see how we can handle exceptions in python using try and except block and use of finally keyword.

Exception Handling

Exception handling is a way of writing code in such a way that,exceptions that can occur at runtime should be handled properly to maintain the normal flow and execution of program.

Suppose I run the below code in which I am trying to open a file called test.txt,which does not exist’s.Look at the output given by python.

open("test.txt")

Output:

Traceback (most recent call last):
File “”, line 1, in
FileNotFoundError: [Errno 2] No such file or directory: ‘test.txt’

As you can see,the output is an error which clearly mentions that there is an error on line number 1 and the error is “FileNotFoundError”.We can use try and except block to handle this kind of errors.

Using Try and Except

Try and Except blocks are used to handle any errors and exceptions in our code.The code which can cause any problem or error is written inside try block and what to do next if the exception is occurred is written inside except block.So lets use try and except block to rewrite above program to handle FileNotFoundError.

try:
    file=open("test.txt")
except Exception:
    print("File not Found")

Output:

File not Found

But,The problem with this way of handling exception is,Exception keyword is generalized for all the errors,means all the errors which will occur will be excepted using except Exception.So,if I change try block as follows,lets see what happens?

try:
    print(a)
except Exception:
    print("File not Found")

Output:

File not Found

As you can see,this time also it’s printing File not Found.But this is wrong,because we are not opening any file here,we are printing a variable a which is not defined,so the error should be NameError.

Traceback (most recent call last):
File “”, line 1, in
NameError: name ‘a’ is not defined

So what we can do?In this case,it is a good practice to except a particular error rather than excepting all the errors with except Exception.We should except the errors which may occur in our code with except followed by error name and except Exception should be used after all the exception so that,if any other error which is not specified by us occurs,will be excepted.So,lets see how we can write this kind of exception handling.

try:
    print(a)
    file=open("test.txt")
except FileNotFoundError:
    print("File Not Found")
except NameError:
    print("Variable not defined")
except Exception:
    print("Some Error Occurred")

In the above code,as we were aware of the errors that might arise when running this program,we excepted that particular errors,i,e, FileNotFounderror if file was not found and NameError if variable is not declared.If other than this two error’s any other error will occur in our program,except Exception will take care of that,and Some Error Occurred will be printed.Output of the above code is:

Output:

Variable not defined

Now,you might be thinking,why File Not Found is not printed if it does not exists.It is because,error are printed in the sequence in which they are found.So,in try block,first line was print(a),and a was not defined,so it’s corresponding error is printed.After any error occurs,execution of program is stopped,hence file not found is not printed.

If I move open(“test.txt”) before print(a) in try block,let’s see the output.

Output:

File Not Found

Note:Always write error specific except block at the top and generalized except block at the bottom,otherwise,if you write generalized error block on top,it will except all the errors that fall under it’s category and stop the execution of program whiteout checking further.For example,lets have a look at below code.

try:
    print(a)
    file=open("test.txt")
except Exception:
    print("Some Error Occured")
except NameError:
    print("Variable not defined")
except FileNotFoundError:
    print("File Not Found")

Output

Some Error Occured

As you can see,it printed Some Error Occured and stopped.But,why is that.Because,Exception is the genearalized keyword which covers all the errors.It is written before NameError and FileNotFoundError.As this line is encounterd,it stops execution of program without checking further and hence Some Error Occured is printed.So,Always write error specific except block at the top and generalized except block at the bottom.

Else block in error handling

Else block is use to define what to do if no error occurs in try block.Let’s see below example.

a=10
try:
    print(a)
except NameError:
    print("Variable not defined") 
except FileNotFoundError:
    print("File Not Found")  
except Exception:
    print("Some Error Occured")
else:
    print("Everything is fine")

As you can see,now I have defined a before starting of try and except block.So,there is no error in try block.As there is no error in try block,no exception will be triggered and program will execute the else block.

Output

10
Everything is fine

Finally keyword

The code written in finally block will be executed,no matter what is going in the try and except block.Code that is critical and should be executed regardless of any error occurs or not,should be written in this block.

try:
    print(a)
    file=open("test.txt")
except Exception:
    print("Some Error Occured")
except NameError:
    print("Variable not defined")
except FileNotFoundError:
    print("File Not Found")
finally:
    print("finally block ran")

Output

Some Error Occured
finally block ran

As you can see,in spite of the error occurred,the finally block is executed.

So,That’a all for this tutorial.I hope,I explained all the concept in detail with proper example.If you have any doubt or suggestion,feel free to comment down below.

Thank You.

Amarjeet

About Amarjeet

Amarjeet,BE in CS ,love to code in python and passionate about Machine Learning and Data Science. Expertsteaching.com is just a medium to share what I have learned till now with world.
Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *