How to Use Try and Except in Python: Step by Step Guide
| Python |
In Python, error handling is essential to create robust programs and prevent them from stopping unexpectedly. To do this, the try and except structure is used.
In this tutorial, you will learn how to use try and except in Python effectively, with practical examples and best practices.
What Are Try and Except in Python?
try and except are control structures that allow you to catch and handle exceptions or errors in Python.
try: Block of code that is attempted.except: Block of code that runs if an error occurs in thetryblock.
This prevents the program from crashing due to an unexpected error.
Basic Syntax
try:
# Code that may cause an error
result = 10 / 0
except ZeroDivisionError:
# Code that runs if an error occurs
print("Cannot divide by zero")
Explanation:
- Python tries to execute the
tryblock. - If a
ZeroDivisionErroroccurs, Python executes theexceptblock. - If no error occurs, the
exceptblock is ignored.
Catching Multiple Exceptions
You can handle different types of errors using multiple except blocks:
try:
number = int(input("Enter a number: "))
result = 10 / number
except ValueError:
print("You must enter a valid number")
except ZeroDivisionError:
print("Cannot divide by zero")
Catching All Exceptions
You can also catch any type of exception:
try:
file = open("nonexistent_file.txt")
except Exception as e:
print(f"An error occurred: {e}")
⚠️ Note: Using
except Exceptioncatches all errors, but it is not recommended to use it always, as it may hide important issues.
Else and Finally Blocks
Python allows using else and finally along with try and except:
try:
number = int(input("Enter a number: "))
result = 10 / number
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("You must enter a valid number")
else:
print(f"The result is {result}")
finally:
print("This block always runs, whether an error occurs or not")
else: Runs if no error occurs.finally: Runs always, useful for releasing resources like files or connections.
Best Practices When Using Try Except
- Catch specific errors, avoid using a generic
exceptunless necessary. - Do not use
tryto control program logic; use it only for handling errors. - Use
finallyto release critical resources (files, database connections). - Add clear messages to help debug errors.
Complete Example: File Handling
try:
with open("data.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("The file does not exist")
except PermissionError:
print("You do not have permission to read the file")
else:
print(content)
finally:
print("Process completed")