There come many situations during the writing of a program that we are not really sure whether the code is correct to perform a specific task. At the same time, we do not want any error situation during runtime because of the same unsure code.

To tackle this type of problem exception handling is used in python. Let’s see what is it and how to implement it in our program.

What is an Exception?

An exception is any unwanted situation which occurs during the runtime of a program. This stops the processing/execution of the program and if not properly handled then can result in a crash.

Example of one such exception in python is:

def add():
    #Intentionally adding an integer with a string
    print(2 + 'a')
    
add()
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Here we tried to add two different types of values and as a result, we got TypeError.

TypeError is one of the type of Built-in-Exception in Python.

To handle these exception- try, except and finally comes handy. Let’s see how each of them work one by one.

Try Except Else in Python

Try Except Else is one of the ways to deal with the exception and to ensure smooth execution of the program.

The code which has the probability of error should be written in try block and the handling of these exceptions should be done in except block. Else only gets executed when there is no excetion in the code inside try block.

Syntax

try:
   Code potential to errors/ecxeption
   ...
except ExceptionI:
   If there is ExceptionI, then this block will be excecuted.
except ExceptionII:
   If there is ExceptionII, then this block will be excecuted.
   ...
else:
   If there is no exception then this block will be excecuted. 

Examples

try:
    def add():
        #Intentionally adding an integer with a string
        print(2 + 'a')
        
    add()
    
except TypeError:
    print("There is a Type Error in the code")
    
else:
    print("No exception found in the code")

Output

There is a Type Error in the code
try:
    def add():
        #Intentionally adding an integer with a string
        print(2 + 'a')
        
    add()
#If you don't know the exception name 
#simply use only except
except:
    print("There was some Error in the code")
    
else:
    print("No exception found in the code")

Output

There was some Error in the code
try:
    def add():
        #Error free
        print(2 + 3)
        
    add()

except:
    print("There was some Error in the code")
    
else:
    print("No exception found in the code")

Output

5
No exception found in the code

Try Except Finally in Python

Finally block always gets executed irrespective of exception in the try block.

Examples

try:
    #file has only read permission
    f = open("file", "r")
    #Trying to write in Read only file
    f.write("Pencil Programmer")
    
except FileNotFoundError:
    print("File Not Found")
    
finally:
    print("Finally code block always gets Executed")

Output

File Not Found
Finally code block always gets Executed
try:
    #file has write permission
    f = open("file", "w")
    f.write("Pencil Programmer")
    
except FileNotFoundError:
    print("File Not Found")
    
finally:
    print("Finally code block always gets Executed")

Output

Finally code block always gets Executed
try:
    #file has only read permission
    f = open("file", "r")
    #Trying to write in Read only file
    f.write("Pencil Programmer")
    
except FileNotFoundError:
    print("File Not Found")

except:
    print("Trouble in reading/writing in file")
    
finally:
    print("Finally code block always gets Executed")

Output

Trouble in reading/writing in file
Finally code block always gets Executed
def integer_input():
    num = 0
    while True:
        try:
            num = int(input("Enter a number "))
        except:
            #Will get executed when input is not a number
            #Exception
            print("Only a number is valid ")
        else:
            #Will get executed when input is a number
            #No exception
            print("Valid Entry! ")
            #To break out of while loop
            break  
        finally:
            print("I am finally block ")
    print("Entered value ",num)

integer_input()

Output

Enter a number five
Only a number is valid 
I am finally block 
Enter a number six
Only a number is valid 
I am finally block 
Enter a number 4
Valid Entry! 
I am finally block 
Entered value  4

Hope now you can use exception handling to handle exceptions using try, except, else and finally block.

Leave a Reply

one × three =