Pages

Wednesday, July 28, 2021

Exception Handling in Python (try - except-else-finally)

Exception Handling in Python

Exception handling is key for any programming language. When an exception occurs Python interpreter stops execution further statements in the program. 

These exceptions could either be related to the Syntax or Data. There are many Built-in exceptions in Python and we can also define user defined exceptions. 

Exception handling in Python can be done by using try - except statements. We can also use else and finally statements depending on how we need to handle the exceptions.

Syntax:

try:

    # Executable statements

except:

    # Statements to execute in case of exception

else:

    # Statements to execute in case of no exception 

finally:

    # Statements to execute irrespective of exception or not


Let's have a look at how to use these statements with few simple examples. 

try and except

try statement should be used in combination of either except or finally. Without these, An exception would occur. 

Let's have a look at the simple division by zero exception (my favorite when it comes to checking exception handling). 

1

2

3

4

a = 10

b = 0

c = a/b

print(c)


Result

Traceback (most recent call last):

  File "/Users/Admin/PycharmProjects/pythonProject/main.py", line 3, in <module>

    c = 10/0

ZeroDivisionError: division by zero



In the above example, 
  • Line - 3: An exception (ZeroDivisionError) is occurred when attempting to divide a with b. 
    • This causes the further statements to not execute. 
We can use try and except statements to handle the exception. 

1

2

3

4

5

6

7

8

try:

   a = 10

   b = 0

   c = a/b

except:

   c = 0

 

print(c)


This is a simple example of handling the exception. 
  • Line - 1: We are using the try statement before the block of code which needs to be monitored for exception. 
    • Lines 2 - 4: Indentation to be followed for the code that should fall under the try statement. 
  • Line - 5: We are using except statement (with no specific exception type) to capture any exception.
    • Line - 6: We are initializing the variable 'c' with zero in case of exception. 
    • This can be replaced with set of statements as required and should follow the indentation. 
  • Line - 8: print statement here would execute with out any error as any exception in the division would be handled with the try and except statements. 

This is a very basic example and we are not using any exception type along with except statement. This would capture all types of exception. 

Let's have a look at different example to open a file and read the content of the file. 

1

2

3

4

notes = open("notes.txt", "r")

notes_content = notes.read()

print(notes_content)

notes.close()


Result


Traceback (most recent call last): File "/Users/Admin/PycharmProjects/pythonProject/main.py", line 1, in <module> notes = open("notes.txt", "r") FileNotFoundError: [Errno 2] No such file or directory: 'notes.txt'


In the above example, we are trying to open a file which does not exist. 
  • Line - 1: An exception is occurred while opening the file which does not exist. 
This causes the following statements to not run. 

Adding try and except statements would capture the error and execute the statements under except block. 

1

2

3

4

5

6

7

try:

   notes = open("notes.txt", "r")

   notes_content = notes.read()

   print(notes_content)

   notes.close()

except:

   print("No file named 'notes.txt'")


In the two examples shared, We are using except statement without mentioning exception type and we are executing different statements for the different exceptions. 

Let's say if the code from both the examples need to be executed as a single block and we need to act based on the exception occurred. 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

try:

   a = 10

   b = 1

   c = a/b

   print(c)

 

   notes = open("notes.txt", "r")

   notes_content = notes.read()

   print(notes_content)

   notes.close()

except ZeroDivisionError:

   c = 0

   print(c)

except FileNotFoundError:

   print("No file named 'notes.txt'")

except:

   print("Error Occurred!")


In the above example, 
  • Lines 1 - 10: try statement followed by the executable statements with the possibility of different exceptions. 
  • Line - 11: We are mentioning 'ZeroDivisionError' along with except statement. This would capture the Division by zero error and runs the block of statements mentioned under this block. 
  • Line - 14: We are mentioning 'FileNotFoundError' along with except statement. This would capture the File not found error and runs the block of statements mentioned under this block.
  • Line - 16: We are using except statement with out any specific exception type. This would capture any error except the two different types of exceptions specifically mentioned. 
Full list of exception types can be found here

else

If there are any set of statements to be executed if no exception occurred, these can be mentioned under the else statement. 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

try:

   a = 10

   b = 1

   c = a/b

   print(c)

 

   notes = open("notes.txt", "r")

   notes_content = notes.read()

   print(notes_content)

   notes.close()

except ZeroDivisionError:

   c = 0

   print(c)

except FileNotFoundError:

   print("No file named 'notes.txt'")

except:

   print("Error Occurred!")

else:

   print("No Error Occurred, Execution is complete!")


In the above example, 
  • Line - 18: We are adding else statement to the try - except. 
    • Block of statements under else would only be executed if the block of code under try is executed without any exception. 

finally

If there are any set of statements to be executed irrespective of the exceptions present or not. These statements can be mentioned under finally statement.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

try:

   a = 10

   b = 1

   c = a/b

   print(c)

 

   notes = open("notes.txt", "r")

   notes_content = notes.read()

   print(notes_content)

   notes.close()

except ZeroDivisionError:

   c = 0

   print(c)

except FileNotFoundError:

   print("No file named 'notes.txt'")

except:

   print("Error Occurred!")

else:

   print("No Error Occurred, Execution is complete!")

finally:

   print("Execution has been completed.")


In the above example, 
  • Line - 20: We are adding finally statement to try - except statements. 
    • Block of statements under finally would be executed irrespective of the exceptions in the code. 

Hope the above info was useful in understanding exception handling in Python. 


If you have any Suggestions or Feedback, Please leave a comment below or use Contact Form.

Exception Handling in Python (try - except-else-finally)

Exception Handling in Python Exception handling is key for any programming language. When an exception occurs Python interpreter stops execu...