Python: Exception Handling


What is an Exception?

In Python, Sometimes the programs may misbehave or terminate/crash unexpectedly due to some unexpected events during the execution of a program. These unexpected events are called as exceptions and the process of handling them to avoid misbehavior or crashing the program is called as exception handling.

Let’s execute the below code in python and have a look at the output.

	def calculate_expenditure(list_of_expenditure):
	    total=0
	    for expenditure in list_of_expenditure:
	        total+=expenditure
	    print(total)
	list_of_values=[100,200,300,"600",500]
	calculate_expenditure(list_of_values)

Above code will give an error, one way to take care of such error situation is to use selection constructs. The error was due to addition of a string (“600”) to an integer. If we add a condition to check whether the expenditure is of type int, that would solve this error.

But that can cause further issues. Let’s see that by executing the below code in python playground.

	def calculate_expenditure(list_of_expenditure):
	    total=0
	    for expenditure in list_of_expenditure:
	        if(type(expenditure) is int):
	            total+=expenditure
	        else:
	            print("Wrong data type")
	            break
	    print(total)
	
	list_of_values=[100,200,300,"600",500]
	calculate_expenditure(list_of_values)

Although we have handled this error using if statement, the function itself returns wrong output when there is error in the input. 
The ideal situation would be if the function can tell us that something went wrong.

try and except

In python we can create a try and except block of code to handle exceptions.
If any exception occurs in the try block of code, it will jump to except block of code. Once the except block is executed, the code continues to execute other statements outside except block.

	def calculate_expenditure(list_of_expenditure):
	    total=0
	    try:
	        for expenditure in list_of_expenditure:
	            total+=expenditure
	        print(total)
	    except:
	        print("Some error occured")
	    print("Returning back from function.")
	
	list_of_values=[100,200,300,"600",500]
	calculate_expenditure(list_of_values)

With this we will not get incorrect output like before.

Built-in Exceptions

Python has many kinds of exceptions predefined as part of the language. BaseException is the base class of all type of exception. Below are some most common types built-in exception.

You can check complete list of built-in exception hierarchy by following link. Python: Built-in Exceptions Hierarchy

Built-in exceptionWhen it will raiseExample
ZeroDivisionErrorWhen a value is divided by zero.num_list=[]
total=0
avg=total/len(num_list)
TypeErrorWhen we try to do an operation with incompatible type.total=10
total+=”20″
NameErrorWhen try to access a variable which is not defined.avg=total/10 #where total is not defined
IndexErrorWhen try to access a index value which is out of range.num_list=[1,2,3,4]
value=num_list[4]
ValueErrorWhen we use a valid data type for an argument of a built-in function but passes an invalid value for itstring is a valid data type for int() but the value “A” is invalid, as “A” can’t be converted into int.
value=”A”
num=int(value)

Python also allows us to handle different exceptions that can occur separately. That means you can have a different action or message for every unique exception that occurs.

Exception Handling Example

Here is the same expenditure calculation code with additional average expenditure calculation.

	def calculate_expenditure(list_of_expenditure):
	    total=0
	    try:
	        for expenditure in list_of_expenditure:
	            total+=expenditure
	        print("Total:",total)
	        avg=total/num_values
	        print("Average:",avg)	    
        except ZeroDivisionError:
	        print("Divide by Zero error")
	    except TypeError:
	        print("Wrong data type")
	    except:
	        print("Some error occured")
	list_of_values=[100,200,300,"400",500]
	num_values=0
	calculate_expenditure(list_of_values)

Note:

  1. Default except block is the one without any type mentioned.
  2. If an error occurs and the matching except block is found, then that is executed.
  3. If an error occurs and the matching except block is not found, it executes the default except block.
  4. If an error occurs and the matching except block is not found and if the default except block is also not found, the code crashes.
  5. The default except block, if present should be the last except block, otherwise it will result in a runtime error.

Exception handling inside a function

If an exception occurs inside a function and if the exception is not caught inside it, then the exception is transferred to the function call. We have another opportunity to catch it, if we write function call inside another try and except block.

Try the below code in python playground and observe the output.

	def calculate_sum(list_of_expenditure):
	    total=0
	    try:
	        for expenditure in list_of_expenditure:
	            total+=expenditure
	        print("Total:",total)
	        avg=total/no_values
	        print("Average:",avg)
	    except ZeroDivisionError:
	        print("Divide by Zero error")
	    except TypeError:
	        print("Wrong data type")
	
	try:
	    list_of_values=[100,200,300,400,500]
	    num_values=len(list_of_values)
	    calculate_sum(list_of_values)
	except NameError:
	    print("Name error occured")
	except:
	    print("Some error occured")

finally

Sometimes in programming we need to execute some code irrespective of whether the primary program logic itself succeeds or fails to do its job. In Python we can achieve this using a finally block. A finally block of statement is an optional part of the try-except statements. A code written inside the finally block will ALWAYS be executed.

finally block is majorly used to close the database connections in the programs which involves database connectivity.

Try the below code in python playground and observe the output.

	balance=1000
	amount="300Rs"
	
	def take_card():
	    print("Take the card out of ATM")
	try:
	    if balance>=int(amount):
	        print("Withdraw")
	    else:
	        print("Invalid amount")
	except TypeError:
	    print("Type Error Occurred")
	except ValueError:
	    print("Value Error Occurred")
	except:
	    print("Some error Occurred")
	finally:
	    take_card()

In this topic you learn about the exception, built-in exceptions and handling of exceptions in different cases.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s