DEV Community

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

Posted on

3 1

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')

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay