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. Multipleexcept
blocks can handle different exceptions.else
(Optional): A block that runs only if thetry
block 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
number
to 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
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours