When writing Python programs, you may face unexpected errors. For example, a user may enter text instead of a number, divide a number by zero, or try to open a file that does not exist.
These errors can stop a program from running. Python provides try and except to help handle such errors.
The try block contains code that may cause an error. The except block tells Python what to do if an error happens.
In this guide, you will learn how try and except work, see simple examples, and understand how to handle common Python errors.
What are Try and Except in Python 2579xao6?
In Python, try and except are used to handle errors.
- Try: Contains code that may cause an error.
- Except: Runs when a matching error happens in the try block.
For example, imagine making a calculator. If someone tries to divide a number by zero, Python shows a ZeroDivisionError.
Using try and except, you can catch this error and show a helpful message instead.
Understanding the Try Block
The try block contains code that Python tries to run.
Example:
try:
result = 10 / 2
print(result)
except ZeroDivisionError:
print("Cannot divide by zero.")
Python runs the code inside the try block. If an error happens, it looks for a matching except block.
Understanding the Except Block
The except block tells Python what to do when a matching error happens.
Example:
try:
result = 10 / 0
except ZeroDivisionError:
print("You cannot divide by zero.")
Output:
You cannot divide by zero.
Python finds the division error and runs the except block.
Why Is Exception Handling Important in Python?
Exception handling helps your program deal with errors in a better way.
Here are some main benefits:
- Keeps programs running: It helps prevent unhandled errors from stopping a program.
- Helps users: It shows clear messages instead of confusing error details.
- Handles wrong input: It helps when users enter the wrong type of information.
- Handles file errors: It helps when a file is missing or cannot be opened.
- Makes code easier to manage: It helps developers understand and fix problems.
Exception handling does not fix every error, but it helps manage many common problems.
What Is the Basic Syntax of Try and Except in Python?
Here is the basic syntax:
try:
# Code that may cause an error
except ExceptionType:
# Code that handles the error
Both try and except need a colon (:). You must also use the correct spaces to keep the code in the right blocks.
Example:
try:
number = int("hello")
print(number)
except ValueError:
print("Please enter a valid number.")
Output:
Please enter a valid number.
Here is what happens:
- Python starts the try block.
- It tries to change
"hello"into a number. - This causes a
ValueErrorbecause"hello"is not a valid number. - Python skips the remaining code in the try block.
- It runs the except block.
- The error message appears.
How Does Try-Except Work in Python?
Python follows a simple process when using try and except.
What Happens When No Error Occurs?
If the code inside the try block runs without an error, Python skips the except block.
Example:
try:
number = 20 / 5
print("Result:", number)
except ZeroDivisionError:
print("Cannot divide by zero.")
print("Program completed.")
Output:
Result: 4.0
Program completed.
There is no error, so Python does not run the except block.
What Happens When an Error Occurs?
If an error happens, Python stops running the remaining code inside the try block. Then, it looks for a matching except block.
Example:
try:
print("Starting calculation")
result = 20 / 0
print("Calculation completed")
except ZeroDivisionError:
print("An error occurred.")
print("Program continues.")
Output:
Starting calculation
An error occurred.
Program continues.
The message "Calculation completed" does not appear because the error stopped the try block.
If Python cannot find a matching except block, the error moves to another handler. If no handler is found, the program stops and shows an error report.

What Are the Common Types of Python Errors?
Python has many built-in error types. Each one tells you about a different problem.
Here are five common examples.
1. ZeroDivisionError
This error happens when you try to divide a number by zero.
try:
result = 15 / 0
except ZeroDivisionError:
print("Cannot divide by zero.")
Output:
Cannot divide by zero.
2. ValueError
This error happens when a value is not correct for an operation.
For example, changing a word into a number causes this error.
try:
age = int("twenty")
except ValueError:
print("Please enter your age as a number.")
3. TypeError
This error happens when you use the wrong types of values together.
try:
result = 10 + "Python"
except TypeError:
print("You cannot add a number and text directly.")
4. NameError
This error happens when you use a variable that Python cannot find.
try:
print(username)
except NameError:
print("This variable has not been defined.")
5. FileNotFoundError
This error happens when you try to open a file that does not exist.
try:
file = open("missing_file.txt", "r")
except FileNotFoundError:
print("The file could not be found.")
Knowing these error types helps you choose the right except block.
How to Handle Multiple Errors in Python
Sometimes, one piece of code can cause different types of errors.
Python lets you use more than one except block to handle them separately.
Example:
try:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
result = num1 / num2
print("Result:", result)
except ValueError:
print("Please enter valid numbers.")
except ZeroDivisionError:
print("You cannot divide by zero.")
If the user enters text instead of a number, Python runs the ValueError block.
If the user enters zero as the second number, Python runs the ZeroDivisionError block.
You can also handle more than one error in a single except block:
try:
value = int("hello")
except (ValueError, TypeError):
print("An invalid value was entered.")
This is useful when you want to show the same message for different errors.
What Does Except Exception as E Mean in Python?
You may see this code in Python programs:
try:
result = 10 / 0
except Exception as e:
print("An error occurred:", e)
Output:
An error occurred: division by zero
Here is what it means:
Exceptionis a common parent class for many Python errors.as esaves the error information in a variable namede.- You can use
eto show the error message.
This can help you understand what went wrong.
However, it is usually better to catch a specific error when you know which error may happen. The Exception class does not catch every type of Python exception.
What Are Else and Finally in Python?
Python also has two useful parts called else and finally.
They help you control what happens after the try block.
What Is the Else Block?
The else block runs only when no error happens in the try block.
Example:
try:
number = int("100")
except ValueError:
print("Invalid number.")
else:
print("Conversion successful!")
print("Number:", number)
Output:
Conversion successful!
Number: 100
The else block is useful when you want to run code only after the try block works successfully.
What Is the Finally Block?
The finally block runs when Python leaves the try statement, whether an error happens or not, during normal program execution.
Example:
try:
number = 10 / 2
print("Result:", number)
except ZeroDivisionError:
print("Cannot divide by zero.")
finally:
print("Calculation finished.")
Output:
Result: 5.0
Calculation finished.
The finally block is often used for cleanup tasks, such as closing files or releasing resources.
Difference Between Else and Finally
| Else | Finally |
|---|---|
| Runs when no error happens in try. | Normally runs whether an error happens or not. |
| Used for successful operations. | Used for cleanup tasks. |
| Does not run if try raises an error. | Runs when control leaves the try statement. |
Real-World Examples of Try and Except in Python
Here are four simple examples that show how try and except are used in real programs.
1. Handling Wrong User Input
Users may enter text when your program needs a number.
try:
age = int(input("Enter your age: "))
print("Your age is:", age)
except ValueError:
print("Please enter a valid number.")
If the user enters the wrong value, Python shows a helpful message.
2. Handling Division by Zero
A calculator should handle attempts to divide by zero.
try:
first = float(input("Enter the first number: "))
second = float(input("Enter the second number: "))
answer = first / second
print("Answer:", answer)
except ZeroDivisionError:
print("You cannot divide by zero.")
except ValueError:
print("Please enter valid numbers.")
This example handles two common errors.
3. Handling Missing Files
Sometimes, a program needs to open a file that is not available.
try:
with open("data.txt", "r") as file:
content = file.read()
print(content)
except FileNotFoundError:
print("The file does not exist.")
The with statement also closes the file automatically when the work is finished.
4. Handling Missing Dictionary Keys
A KeyError happens when you try to get information from a dictionary using a key that does not exist.
student = {
"name": "John",
"age": 21
}
try:
print(student["grade"])
except KeyError:
print("This information is not available.")
Output:
This information is not available.

Python Try-Except Best Practices
Follow these simple tips when using try and except:
- Catch specific errors: Use the correct error type instead of catching every error.
- Avoid bare except: Do not use
except:without an error type unless you have a special reason. - Keep try blocks small: Only put the code that may cause the expected error inside the try block.
- Show clear messages: Tell users what went wrong and how they can fix it.
- Use else when needed: Keep successful operations separate from error-handling code.
- Use with for files: It closes files automatically.
- Record unexpected errors: Use logging when you need to find and fix problems in larger programs.
These tips make your Python code easier to read and manage.
Common Try-Except Mistakes to Avoid
Beginners often make these mistakes:
- Forgetting the colon: Always add
:aftertryandexcept. - Wrong indentation: Keep code inside the correct block.
- Using the wrong error type: Choose the exception that matches the problem.
- Using broad except blocks: Catching too many errors can hide other problems.
- Wrong order of except blocks: Put specific errors before general ones.
- Thinking try-except fixes everything: It handles matching exceptions but does not fix all programming mistakes or syntax errors.
Avoiding these mistakes will help you write better Python programs.
Conclusion
Try and except are important parts of Python. They help programs handle errors in a better way.
The try block contains code that may cause an error, while the except block tells Python what to do when that error happens.
You can also use multiple except blocks, else, and finally to handle different situations.
Start by practicing simple examples, such as wrong user input and division by zero. As you learn more, try handling file errors and other common problems. With practice, you will become better at writing Python programs that handle errors correctly.
Frequently Asked Questions About Try and Except in Python
What are try and except in Python?
Try and except are Python keywords used to handle errors. The try block contains code that may cause an error, while the except block handles a matching error.
Why do programmers use try and except?
Programmers use them to handle errors, show helpful messages, and stop unhandled errors from interrupting normal program execution.
Can Python have multiple except blocks?
Yes. You can use multiple except blocks to handle different errors separately.
Can you use try without except in Python?
Yes. You can use try with finally without an except block. However, a try statement must have at least one except or finally clause.
What happens if an error is not caught?
Python looks for another matching error handler. If none is found, it shows an error report and stops the affected program execution.
What is the difference between except and finally?
The except block handles errors. The finally block runs when Python leaves the try statement and is often used for cleanup tasks.
Does try-except prevent all program errors?
No. It handles matching errors that happen while the program runs. It does not prevent every error or fix problems in your code.
You May Also Like:
DH58GOH9.7 Code: Meaning, Uses, Safety, and How to Verify It
Information About FoxTPAX Software: Features, Uses, Safety, and What to Know in 2026
Disclaimer:
This article is for informational and educational purposes only. The Python examples are shared to help readers learn. Some images may be AI-generated for illustrative purposes. All copyrights and trademarks belong to their respective owners. Brand names are used only to identify related products or services.