Difference between finally and else in Python

Finally and Else in Python are part of Exception control flow.

Exception means the errors raised. In Python, it may be raised in various ways, like when we pass an invalid argument to any function or while executing an illegal operation or may be due to bad indentation. 

When an exception is encountered, it stops the program execution and print Traceback and also tells what the exception is and what caused the exception to be raised. But, we have a special thing “try statement” to catch an exception and to prevent the program from a crash. 

Else

Else code comes into execution only when there is no exception raised in the try block. The code inside this block is the same as normal code. If an exception is raised then this block will not run and may stop the program.

Remember, when else block will be executed than except block will not be executed and the inverse is also true. Else block is an optional block. We will see the code, how it works.

Finally

This code executes at the last when all other blocks have completed execution, it will work even if there was no exception or an uncaught exception or there is a return statement in any of the other above blocks, it will run in every case.

The code inside it is just a normal code. Same as else block, this block is also an optional block but if there comes an exception it will still run. We will see the code, how it works.

Python code to demonstrate the difference between else and finally

We have written the code with try and except and shown how the else and final block works

def func1():
   try:
          1 / 0
   except:

         print('‘An Exception was caught’')
   else:
       print("No Exception raised")
print("result of func1 is :")
func1()
print(" ")

def func2():
   try:
          1 + 0
   except:

         print('‘An Exception was caught’')
   else:
       print("No Exception raised")
print("result of func2 is :")
func2()
print(" ")

def func3():
   try:
       1 + 0
   except:
       return 0
   else:
       return 1
   finally:
         print("finally completed")
print("result of func3 is :")
func3()
print(' ')

def func4():
   try:
       1 / 0
   except:
       print("An Exception was caught")
   else:
       return 1
   finally:
         print("finally completed")
print("result of func4 is :")
func4()

 

Output

result of func1 is :
‘An Exception was caught’

result of func2 is :
No Exception raised

result of func3 is :
finally completed

result of func4 is :
An Exception was caught
finally completed

[Program finished]

 

You may also make other functions and try to make changes yourself. I hope you understood the concept and how the program actually works. Try to run the code and if you have any problem leave a comment. Your feedback will be appreciated.

Leave a Reply

Your email address will not be published. Required fields are marked *