Python Tutorial

Python Try Except: Except Else and Except Finally

Try Except in Python Explained

Exceptions are captured and managed using Python try and except statements. The try clause contains statements that may cause an exception to be raised, whereas the except clause contains statements that deal with the exception.

Python Try Except Else

You can utilise the else clause on the try-except block in Python, which must come after all the except clauses. In case the try clause doesn’t throw an exception, the function moves to the else block.

Example:

Try with else clause

# Program to depict else clause with try-except

# Python 3

# Function which returns a/b

def AbyB(a , b):

    try:

        c = ((a+b) / (a-b))

    except ZeroDivisionError:

        print ("a/b result in 0")

    else:

        print (c)

# Driver program to test above function

AbyB(2.0, 3.0)

AbyB(3.0, 3.0)

Output:

-5.0
a/b result in 0

Python Try Except Finally

Finally is a Python keyword that executes after the try and except blocks. When the try block has concluded normally or due to an exception, the final block is always executed.

Example:

try:

    x = 4//0 

    print(x)

except ZeroDivisionError:

    print("Can't divide by zero")

finally:

    print('This is always executed')

Output:

Can't divide by zero
This is always executed
Did you find this article helpful?