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

try:
    # code that may raise exception 
except:
    # code that handle exceptions
else:
    # execute if no exception
finally:
    # 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.

Example

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

Output

example

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

Summary

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.


Similar Articles