else keyword in exception handling

The else keyword in Python in the context of exception handling is provided for the no exception, no return, no continue and no break scenario.For the try block else block is an optional one.

Keywords Updated 23 May 2019 1 min read

Overview

Example

python
def div(param1, param2):

     quotient = param1/param2;

     return quotient;

try:

    p1 = 1;

    p2 = 100;

    n1 = div(p1,p2);

    print("p1/p2 is %d"%n1);

    p1 = 2;

    p2 = 100;

    n1 = div(p1,p2);

    print("p1/p2 is %d"%n1);

except Exception as Ex:

    print("Exception: %s"%Ex);

else:

    print("All div operations successful");

Output

Output
p1/p2 is 0

p1/p2 is 0

All div operations successful