Python Exception Handling

Author: Al-mamun Sarkar Date: 2020-03-25 16:10:04

Python Exception Handling. The following code shows how to handle exception in python using try and catch. 

try:
    with open('test.txt', 'r') as my_file:
        content = my_file.read()
        print(content)
except:
    print('The file does not exist.')
print('Made by Mamun.')

 

Output:

The file does not exist.
Made by Mamun.

 

 

Another Example:


try:
    my_list = []
    print(my_list[0])
except IndexError as e:
    print(e)

 

Output:

list index out of range