Try..Except..Else..Finally In Python

What Is Exception?

Exception is an unwanted or unexpected event, which occurs during the execution of a program, i.e. at run time, that disrupts the normal flow of the program's instructions.

What Is Exception Handling?

The Exemption Handling within Python is one of the capable component to handle the runtime errors so that the normal flow of the application can be maintained.

Exception Handing In Python

In Python we handle the exception using try..except..finally

Syntax For try..except..finally

    # code that may raise exception 
    # code that handle exceptions
    # execute if no exception
    # code that clean up

Understand the execution of above syntax

First try block is executed

If error occurs then except block is executed.

If no error occurs then else block will be executed.

The finally block will always exceute if error occurred or not.


def division(x, y):
        res = x / y
        print("Error - Divided by Zero")
        print("Your answer is :", res)
        print('Finally Block Is Always Executed') 
division(15, 5)
division(5, 0)



Understand the output

First, we call the division function with value 15 and 5, so 15 is divisible by 5 so no error occurs and try block execute successfully, and then after else block also execute successfully.

Second, we call the division function with value 5 and 0, so function try to divide 5 by 0 but we can not divide any value with 0 so except block execute and else block not executed.

And in both cases finally block is executed


The try block is used to enclose the code that might throw an exception.

The except block lets you handle the error.

The else block is executed when no exception occurred.

The finally block is a block used to execute important code such as closing the connection.