Python: Handle Exception using Try, Except & Finally

python programs

We programmers are sometimes not sure about the correctness of our code. For example, writing a python code to fetch data from the online server over HTTP (HTTP request could fail because of no internet connection).

In such situations, we need to handle these exceptions in advance in order to prevent the program from crashing.

In this tutorial, we will learn what exception is in Python and what are the ways to handle them.

What is an Exception?

An exception in context to programming is any unwanted situation or error that occurs during the runtime of the program. It can stop the processing/execution of the program and could result in a crash if not handled properly.

In Python, an exception is represented as an object.

When an exception occurs, the Python interpreter generates and outputs the error message along with the object, signifying the type of exception.

An example of one such exception in Python is TypeError.

This exception occurs when we try to perform any action on unsupported types. For example, adding an integer with a string value:

def add():
    #intentionally adding an integer with a string
    print(2 + 'a')
    
add()

Output:

TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’

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

Types of Exception in Python

Like TypeError, there are many other exceptions that come built-in with Python. However, we can also create exceptions of our own.

Therefore, exceptions in Python can be categorized as:

  1. Built-in-Exception
  2. Used-defined-Exception

How to Handle Exceptions in Python?

To handle exceptions from crashing the program execution, we use try, except, else, and finally clause. Let’s see how can we use them one by one.

Try, Except, Else

The try, except & else is one of the ways to deal with the exception in Python.

The general syntax for try, Except, and else is:

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...

We write that set of statements inside the try block which is prone to error (the code that could potentially throw an error).

The try block must be followed by the except block (or blocks).

Although we can write multiple except blocks, only one gets executed depending on the type of exception.

Therefore, the except block should contain the code that will run in response to the event of the specified Exception.

It is important to note that the except block only executes in the event of the exception. If no exception occurs then no except block is invoked.

The else block is optional. It is executed when there is no exception in the code of the try block.

Therefore, we should write that set of statements inside the else block which should be executed only if there is no error.

Example 1:

try:
    #Intentionally adding an integer to a string
    print(2 + 'a')
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.

Example 2:

We can handle all types of Exception in a single except block by not specifying any type.

try:
    #Intentionally adding an integer to a string
    print(2 + 'a')
'''
In case, you don't know the name of the exception or
want to handle all types of Exception in single except block,
then don't specify any type
'''
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.

Example 3:

try:
    print(2 + 3)
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

Finally

The finally block is an optional block that follows the except or else block.

It is invoked irrespective of whether the exception occurs or not in the try block.

The finally block should contain the statements that should always run no matter whether any Exception had occurred.

Example 1:

try:
    #file has only read permission
    f = open("file", "r")
    #trying to write to a '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

Example 2:

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.

Example 3:

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 a file")
finally:
    print("Finally, code block always gets Executed")

Output:

Trouble in reading/writing in a file
Finally, code block always gets Executed

Example 4:

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

Leave a Reply

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