Skip to content

Try keyword in Python

  • by

The Python Try keyword is used to check errors in a block of code. It is used with try…except blocks. In Python, exceptions can be handled using a try statement.

Try keywords in Python

A simple example code will raise an error because the variable “price” is not defined.

try:
    price > 3
except:
    print("Something went wrong")

print("Outside try program keeps running")

Output:

Try keywords in Python

Print an exception in Python

try:
    price > 3
except Exception as e:
    print(e)

Output: name ‘price’ is not defined

Do comment if you have any doubts or suggestions on this Python keywords topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *