try

In Python, the try keyword defines a block of code that you want to attempt to execute while also providing a way to handle exceptions that may occur during its execution. The try block is typically followed by one or more except blocks to catch and handle exceptions. It’s a fundamental tool for managing errors and exceptions gracefully in your Python code.

Python try Keyword Examples

Here’s a quick example of using the try keyword with an except block:

Python
>>> try:
...     result = 10 / 0
... except ZeroDivisionError:
...     print("To infinity and beyond...")
...
To infinity and beyond...

In this example, the code inside the try block attempts to divide 10 by 0, which raises a ZeroDivisionError. The except block catches this exception and prints a message.

Python try Keyword Use Cases

  • Handling exceptions that may occur during file operations, such as reading or writing to a file
  • Managing errors in network operations, like making requests to external services
  • Catching and dealing with arithmetic errors, such as division by zero

Tutorial

Python Exceptions: An Introduction

In this beginner tutorial, you'll learn what exceptions are good for in Python. You'll see how to raise exceptions and how to handle them with try ... except blocks.

basics python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Jan. 6, 2025 • Reviewed by Dan Bader