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 playground 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,"400",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 (“400”) 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,"400",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.
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,"400",500] calculate_expenditure(list_of_values)
With this we will not get incorrect output like before.
Python has many kinds of exceptions predefined as part of the language. Here are some of the common types.
Built-in exception | When it will be raised | Example |
---|---|---|
ZeroDivisionError | When a value is divided by zero | num_list=[] total=0 avg=total/len(num_list) |
TypeError | When we try to do an operation with incompatible data types | total=10 total+=“20” |
NameError | When we try to access a variable which is not defined | avg=total/10 where total is not defined |
IndexError | When we try to access an index value which is out of range | num_list=[1,2,3,4] value=num_list[4] |
ValueError | When we use a valid data type for an argument of a built-in function but passes an invalid value for it | #string 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.
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 :
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")
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()
All Rights Reserved. © 2024 BookOfNetwork