Introduction

Python programmers have a powerful tool at their disposal in the form of try..except..else. This feature enables us to tackle unexpected errors and find efficient ways of handling them, leading to smoother functioning codes. This tutorial will provide you with a detailed insight into the try..except..else construct, its syntax, and its various use cases. So, tighten your seat belts and let's get started!

Table of Contents :

  • try..except..else in Python 
  • Control flow of try...except...else statement

try..except..else in Python :

  • We have already read how try...except construct is used to handle exceptions in Python.
  • There is an optional else clause of the try..except statement.
  • The code in the else block is executed if no exception occurs in try block.
  • If exception occurs in try block, the except block is executed and else block is ignored.
  • Difference between else block and finally block :
    • The code in the finally block is always executed, whether an exception occurs or not.
    • The code in the else block is executed only if no exception occurs in try block.
  • If in case we have finally block as well, the else block is executed after try block and before finally block.

Control flow of try...except...else statement :

  • code in try block is executed.
  • If exception occurs in try block - 
    • the rest of the statements of the try block are ignored.
    • code in the except block is executed.
  • If no exception occurs in try block - 
    • All statements in try block are executed.
    • Code in the else block is executed.
  • Lastly the code in finally block is executed.
  • Code Sample : 

def my_function(x, y):
    try:
        print("Inside try block")
        z = (x * y) / (x + y)
        print("Value of z = ", z)
    except Exception as e:
        print("Inside except block : ", e)
    else:
        print("Inside else block")
    finally:
        print("Inside Finally block")



my_function(5, -5)
print()
my_function(4, 1)


# Output
# Inside try block
# Inside except block :  division by zero
# Inside Finally block

# Inside try block
# Value of z =  0.8
# Inside else block
# Inside Finally block



Prev. Tutorial : Finally block

Next Tutorial : Raising exceptions