Handling Exceptions in Python
I this tutorial we are going to learn exception handling in Python and experiment with some of the examples.
What is Exception?
An exception is an event or error, which arises during the execution of a program, that interrupts the usual flow of the instructions of the program.
Error -
Error is an operation performed by the user which is not allowed, which results in abnormal working of the program or not working of the program at all.
There are different types of errors and the major errors are -
IndexError -
This error occurs when the index of a sequence is out of range.
For ex -
fruit_list = ['Apple', 'Banana', 'Pear'] fruit = fruit_list[5] |
As you can see in the program there is a list of fruits which contains 3 values. And in the second line of code we are accessing the value from fruit_list at the index 5 (fruit_list[5]) which does not exist.
Output of the above code will look like this -
IndexError: list index out of range |
KeyError -
This error occurs when a key is not found in a dictionary.
For ex-
a_dictionary = {'key1': 'value1'} value = a_dictionary['non_existing_key'] |
As you can see in the code above, the dictionary called a_dictionary is created with the key as key1 and the value as value 1.
To fetch the value of a key we have to provide a name of the key of that value.
In this case the key called non_existing_key does not exist in the a_dictionary. So it will raise a KeyError.
Output of the code look like this -
KeyError: 'non_existing_key'] |
TypeError -
This error occurs when a function or operation is applied to an object of different datatype or an incorrect type.
For ex -
text = 'abcd' print(text + 5) |
In the above code the text object contains data of string type and in the next line we are adding the string with an integer which is not allowed so it will show the TypeError if we run the code.
Output of the code will look like this -
TypeError: can only concatenate str (not "int") to str |
There are more common exceptions built into python like this. each one describes different type of problem
Let’s learn how to handle exceptions when they occur and raise exceptions when necessary.
The general way of handling the exceptions is try, except, else, finally construction. 0
For example we will use the FileNotFoundError -
try: except FileNotFoundError: else: finally: |
Try -
In the above code we have used try and except block. In the try block it will check if the a_file.text exists or not.
2
except -
If the file mentioned in the try block does not exist then instead of showing the FileNotFoundError it will go into the except block and create a file called a_file.text. It’s almost like an if else statement.
We have to provide the name of the Error after the except keyword because if there are multiple errors in the try block it will ignore other errors.
else -
Else block executes when the thing which you are in the try block succeeds. Which means only if no exceptions are occurred then it will go to the else block
3
finally -
The last block is finally. This is the code that's going to run no matter what happens in your code.
Here more examples of Python: