DEV Community

Cover image for Beginner Python tips Day - 06 try...except...else...finally
Paurakh Sharma Humagain
Paurakh Sharma Humagain

Posted on

Beginner Python tips Day - 06 try...except...else...finally

# Python Day 06 - try...except...else...finally

# try, except(also known as catch) and finally pattern is seen in many programming language
# but on top of that Python comes with else block as well,
# else block runs before finally block
# when there is no exception in the try block

# Example 1

try:
    print(100/0)
    # Doesn't print anything because there is an exception
except ZeroDivisionError:
    print('This does run as there is ZeroDivisionError')
else:
    print("This doesn't run as there is an exception in try block")
finally:
    print('This runs regardless of the exception')

# Example 2

try:
    print(100/5)
    # Prints 20.0
except ZeroDivisionError:
    print("This doesn't run as there is no ZeroDivisionError")
else:
    print("This runs as there is no exception in try block")
finally:
    print('This runs regardless of the exception')

Latest comments (0)