Python try
Anonymous contributor
Published Jun 17, 2025
Contribute to Docs
The try keyword in Python is used to define a code block that may raise an exception, allowing errors to be caught and handled gracefully with except, and optionally complemented by else and finally clauses.
Syntax
try:
# Code that might raise an exception
except ExceptionType:
# Code to handle the exception
else:
# (Optional) Code to run if no exceptions occur
finally:
# (Optional) Code that always runs
In the syntax:
except(Optional): Specifies the type of exception to catch. Multipleexceptblocks can handle different exceptions.else(Optional): A block that runs only if thetryblock doesn’t raise an exception.finally(Optional): A block that always runs, regardless of whether an exception occurred or not.
Return value:
The try statement itself does not return a value. It controls the flow of execution by handling exceptions within its block.
Example: Handling Division Error with try-except
This example shows how to catch a ZeroDivisionError using a simple try-except block:
try:x = 10 / 0except ZeroDivisionError:print("Cannot divide by zero.")
The output of this code will be:
Cannot divide by zero.
Codebyte Example: Handling Multiple Exceptions with try-except-finally
This codebyte example captures both invalid input and division-by-zero errors while ensuring a final message always prints:
Note: Change the value entered for
numberto see different results and exception handling in action.
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours