ℹ️ Skipped - page is already crawled
| Filter | Status | Condition | Details |
|---|---|---|---|
| HTTP status | PASS | download_http_code = 200 | HTTP 200 |
| Age cutoff | PASS | download_stamp > now() - 6 MONTH | 2 months ago |
| History drop | PASS | isNull(history_drop_reason) | No drop reason |
| Spam/ban | PASS | fh_dont_index != 1 AND ml_spam_score = 0 | ml_spam_score=0 |
| Canonical | PASS | meta_canonical IS NULL OR = '' OR = src_unparsed | Not set |
| Property | Value |
|---|---|
| URL | https://serveracademy.com/blog/python-try-except/ |
| Last Crawled | 2026-02-13 21:41:54 (1 month ago) |
| First Indexed | 2025-03-08 20:12:34 (1 year ago) |
| HTTP Status Code | 200 |
| Meta Title | Python Try Except - Server Academy |
| Meta Description | When writing Python code, errors can be frustrating. Luckily, Python’s try and except blocks provide an effective way to manage errors without breaking the flow of your code. The try and except statements let you handle specific exceptions, print error messages, and even use else and finally blocks for more… |
| Meta Canonical | null |
| Boilerpipe Text | When writing Python code, errors can be frustrating. Luckily, Python’s
try
and
except
blocks provide an effective way to manage errors without breaking the flow of your code. The
try
and
except
statements let you handle specific exceptions, print error messages, and even use
else
and
finally
blocks for more control.
In this guide, we’ll explore how to use
try
,
except
,
else
, and
finally
effectively to write robust and error-tolerant Python code.
What Is
try
and
except
in Python?
In Python,
try
and
except
are used to catch and handle exceptions, allowing your program to continue executing or provide custom error messages rather than crashing. Here’s a basic syntax for using
try
and
except
:
try:
# Code that might raise an exception
except SomeException:
# Code to run if the exception occurs
Example Usage
Let’s look at a simple example to handle division by zero:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
Output:
Cannot divide by zero!
In this example, the
try
block contains code that could potentially raise a
ZeroDivisionError
. When this error occurs, the code in the
except
block runs, printing a helpful message.
Catching Specific Exceptions in Python
In Python, you can catch specific exceptions to handle different error types individually. This allows you to create custom responses for each error type and manage multiple errors gracefully.
try:
value = int("abc")
except ValueError:
print("Invalid number format!")
except TypeError:
print("Unsupported operation!")
Output:
Invalid number format!
Here,
try
and
except
are used to handle a
ValueError
(raised by trying to convert a string to an integer) with a custom error message. You can add as many specific
except
blocks as needed.
Using
try
and
except
with
else
In Python, the
else
block is used with
try
and
except
to define code that runs only if no exceptions occur in the
try
block. This is helpful when you want to perform certain actions only when the code in the
try
block is successful.
try:
number = int("42")
except ValueError:
print("Conversion failed!")
else:
print("Conversion successful:", number)
Output:
Conversion successful: 42
In this example,
else
only runs if the
try
block completes without error. If an exception occurs, the
else
block is skipped.
Printing Errors in Python Try Except
Sometimes, you want to print the exact error message rather than a generic one. Python’s
except
block allows you to capture the error message using the
as
keyword.
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error occurred: {e}")
Output:
Error occurred: division by zero
By using
as e
, you can access the exception message, which provides specific details about the error that occurred.
Using
try
,
except
, and
finally
in Python
The
finally
block runs regardless of whether an exception occurs or not. This is useful for cleanup tasks, such as closing files or releasing resources, that need to happen regardless of success or failure.
try:
file = open("sample.txt", "r")
data = file.read()
except FileNotFoundError:
print("File not found!")
finally:
file.close()
print("File closed.")
Output:
File not found!
File closed.
In this example, the
finally
block closes the file, ensuring the resource is released even if an error occurs. The
finally
block is a helpful way to maintain resource integrity in your programs.
Practical Examples of Using
try
,
except
,
else
, and
finally
Example 1: Handling Multiple Exceptions
Here’s an example of using
try
,
except
,
else
, and
finally
to handle multiple exceptions in a single block:
try:
number = int(input("Enter a number: "))
result = 10 / number
except ValueError:
print("Invalid input! Please enter a numeric value.")
except ZeroDivisionError:
print("You cannot divide by zero!")
else:
print("Division successful! Result is:", result)
finally:
print("Program execution completed.")
Output if the user enters “0”:
You cannot divide by zero!
Program execution completed.
Output if the user enters “abc”:
Invalid input! Please enter a numeric value.
Program execution completed.
In this example:
try
contains code that could raise a
ValueError
or
ZeroDivisionError
.
except
catches these errors separately and provides specific error messages.
else
only runs if no exception occurs, and
finally
always runs, printing a completion message.
Example 2: Using
try
,
except
, and
finally
with Resource Management
When working with files, databases, or network connections,
try
,
except
, and
finally
are invaluable for ensuring resources are properly closed, even if errors occur.
try:
with open("data.txt", "r") as file:
data = file.read()
except FileNotFoundError as e:
print(f"Error: {e}")
else:
print("File content successfully read!")
finally:
print("Resource handling complete.")
Output:
Error: [Errno 2] No such file or directory: 'data.txt'
Resource handling complete.
Using
with open
automatically closes the file after reading, but the
finally
block provides a good spot for additional cleanup or logging.
Conclusion
The
try
and
except
blocks in Python help you gracefully handle errors, while the
else
and
finally
blocks provide more control over your code’s flow. Here’s a quick recap of each component:
try
: Contains the code that might raise an exception.
except
: Catches and handles specific exceptions, letting you respond to errors.
else
: Runs if no exceptions occur, useful for actions that rely on the success of
try
.
finally
: Runs regardless of success or failure, ideal for cleanup actions.
Mastering
try
,
except
,
else
, and
finally
will help you write Python code that’s resilient and easier to troubleshoot, improving the overall quality of your programs.
Want to advance your Python programming skills? Enroll in our Python course by clicking the link below:
Free Course: Python 3 for Beginners
Python is one of the most used programming languages in the world. Both the popularity and the deman…
50 Lessons
1 Quizzes
1 Labs
5 Hr
Now that you know the basics, try incorporating
try
and
except
in your own projects to see how it simplifies error handling and keeps your code running smoothly. |
| Markdown | 

Login
[Skip to content](https://serveracademy.com/blog/python-try-except/#fl-main-content)
[](https://serveracademy.com/)
- [](https://serveracademy.com/)
- [PLANS](https://serveracademy.com/pricing)
- [COURSES](https://serveracademy.com/courses/)
- [FREE BEGINNER COURSES](https://serveracademy.com/blog/python-try-except/)
- [ Active Directory Fundamentals](https://serveracademy.com/courses/active-directory-fundamentals/)
- [ Building your IT Lab](https://serveracademy.com/courses/building-your-it-lab/)
- [ Linux Fundamentals](https://serveracademy.com/courses/linux-fundamentals/)
- [Create Free Account](https://serveracademy.com/signup-free)
- [INTERMEDIATE COURSES](https://serveracademy.com/blog/python-try-except/)
- [ Windows Server](https://serveracademy.com/courses/installing-and-configuring-windows-server/)
- [ Active Directory](https://serveracademy.com/courses/active-directory-identity-with-windows-server/)
- [ Group Policy](https://serveracademy.com/courses/group-policy-security-with-windows-server/)
- [ Windows DNS](https://serveracademy.com/courses/installing-and-configuring-domain-name-system-dns/)
- [Windows Dynamic Host Control Protocol (DHCP)](https://serveracademy.com/courses/installing-and-configuring-dhcp/)
- [ Linux Server Administration](https://serveracademy.com/courses/linux-server-administration/)
- [Python 3 Fundamentals](https://serveracademy.com/courses/python-3-for-beginners/)
- [Introduction to AWS (Amazon Web Services)](https://serveracademy.com/courses/introduction-to-aws-amazon-web-services/)
- [ADVANCED COURSES](https://serveracademy.com/blog/python-try-except/)
- [ Windows PowerShell](https://serveracademy.com/courses/administration-and-automation-with-windows-powershell/)
- [ Windows Server Update Services](https://serveracademy.com/courses/installing-and-configuring-windows-server-update-services-wsus/)
- [Installing and Configuring System Center Configuration Manager (SCCM)](https://serveracademy.com/courses/installing-and-configuring-system-center-configuration-manager-sccm/)
- [FEATURES](https://serveracademy.com/features/)
- [COURSES](https://serveracademy.com/curriculum/)
- [IT LABS](https://serveracademy.com/it-labs/)
- [ARCHER AI](https://serveracademy.com/archer-ai/)
- [FOR BUSINESS](https://serveracademy.com/business/)
- [RESOURCES](https://serveracademy.com/blog/python-try-except/)
- [BLOG](https://serveracademy.com/blog/)
- [DISCOURSE](https://community.serveracademy.com/)
- [DISCORD](https://discord.gg/w9BFAzNTYC)
- [CONTACT](https://serveracademy.com/contact/)
- [LOGIN](https://serveracademy.com/blog/python-try-except/#login)
- [SIGN UP FREE](https://serveracademy.com/signup-free/)

First Name
Last Name
Email
I forgot my password
Password
Sign up free
Or sign in using
Google
***
Don't have an account yet?
Create a free account
Sign in instead

Please wait...
# Python Try Except
When writing Python code, errors can be frustrating. Luckily, Python’s try and except blocks provide an effective way to manage errors without breaking the flow of your code. The try and except statements let you handle specific exceptions, print error messages, and even use else and finally blocks for more…

Paul Hill
12 November, 2024 - 7.5 min read
[](https://serveracademy.com/blog-sign-up-now/)
Table of Contents
Add a header to begin generating the table of contents
Related Courses
[ Ansible Training for Beginners Paul Hill](https://serveracademy.com/courses/ansible-for-complete-beginners/)
[ Building your IT Lab Paul Hill - **FREE COURSE**](https://serveracademy.com/courses/building-your-it-lab/)
[ Administration and Automation with Windows PowerShell Paul Hill, Robert Hill](https://serveracademy.com/courses/administration-and-automation-with-windows-powershell/)
[ Python 3 for Beginners Paul Hill - **FREE COURSE**](https://serveracademy.com/courses/python-3-for-beginners/)
[View All Courses](https://serveracademy.com/courses)
When writing Python code, errors can be frustrating. Luckily, Python’s `try` and `except` blocks provide an effective way to manage errors without breaking the flow of your code. The `try` and `except` statements let you handle specific exceptions, print error messages, and even use `else` and `finally` blocks for more control.
In this guide, we’ll explore how to use `try`, `except`, `else`, and `finally` effectively to write robust and error-tolerant Python code.
## What Is `try` and `except` in Python?
In Python, `try` and `except` are used to catch and handle exceptions, allowing your program to continue executing or provide custom error messages rather than crashing. Here’s a basic syntax for using `try` and `except`:
```
try:
# Code that might raise an exception
except SomeException:
# Code to run if the exception occurs
```
### Example Usage
Let’s look at a simple example to handle division by zero:
```
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
```
Output:
```
Cannot divide by zero!
```
In this example, the `try` block contains code that could potentially raise a `ZeroDivisionError`. When this error occurs, the code in the `except` block runs, printing a helpful message.
## Catching Specific Exceptions in Python
In Python, you can catch specific exceptions to handle different error types individually. This allows you to create custom responses for each error type and manage multiple errors gracefully.
```
try:
value = int("abc")
except ValueError:
print("Invalid number format!")
except TypeError:
print("Unsupported operation!")
```
Output:
```
Invalid number format!
```
Here, `try` and `except` are used to handle a `ValueError` (raised by trying to convert a string to an integer) with a custom error message. You can add as many specific `except` blocks as needed.
## Using `try` and `except` with `else`
In Python, the `else` block is used with `try` and `except` to define code that runs only if no exceptions occur in the `try` block. This is helpful when you want to perform certain actions only when the code in the `try` block is successful.
```
try:
number = int("42")
except ValueError:
print("Conversion failed!")
else:
print("Conversion successful:", number)
```
Output:
```
Conversion successful: 42
```
In this example, `else` only runs if the `try` block completes without error. If an exception occurs, the `else` block is skipped.
## Printing Errors in Python Try Except
Sometimes, you want to print the exact error message rather than a generic one. Python’s `except` block allows you to capture the error message using the `as` keyword.
```
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error occurred: {e}")
```
Output:
```
Error occurred: division by zero
```
By using `as e`, you can access the exception message, which provides specific details about the error that occurred.
## Using `try`, `except`, and `finally` in Python
The `finally` block runs regardless of whether an exception occurs or not. This is useful for cleanup tasks, such as closing files or releasing resources, that need to happen regardless of success or failure.
```
try:
file = open("sample.txt", "r")
data = file.read()
except FileNotFoundError:
print("File not found!")
finally:
file.close()
print("File closed.")
```
Output:
```
File not found!
File closed.
```
In this example, the `finally` block closes the file, ensuring the resource is released even if an error occurs. The `finally` block is a helpful way to maintain resource integrity in your programs.
## Practical Examples of Using `try`, `except`, `else`, and `finally`
### Example 1: Handling Multiple Exceptions
Here’s an example of using `try`, `except`, `else`, and `finally` to handle multiple exceptions in a single block:
```
try:
number = int(input("Enter a number: "))
result = 10 / number
except ValueError:
print("Invalid input! Please enter a numeric value.")
except ZeroDivisionError:
print("You cannot divide by zero!")
else:
print("Division successful! Result is:", result)
finally:
print("Program execution completed.")
```
Output if the user enters “0”:
```
You cannot divide by zero!
Program execution completed.
```
Output if the user enters “abc”:
```
Invalid input! Please enter a numeric value.
Program execution completed.
```
In this example:
- **`try`** contains code that could raise a `ValueError` or `ZeroDivisionError`.
- **`except`** catches these errors separately and provides specific error messages.
- **`else`** only runs if no exception occurs, and **`finally`** always runs, printing a completion message.
### Example 2: Using `try`, `except`, and `finally` with Resource Management
When working with files, databases, or network connections, `try`, `except`, and `finally` are invaluable for ensuring resources are properly closed, even if errors occur.
```
try:
with open("data.txt", "r") as file:
data = file.read()
except FileNotFoundError as e:
print(f"Error: {e}")
else:
print("File content successfully read!")
finally:
print("Resource handling complete.")
```
Output:
```
Error: [Errno 2] No such file or directory: 'data.txt'
Resource handling complete.
```
Using `with open` automatically closes the file after reading, but the `finally` block provides a good spot for additional cleanup or logging.
## Conclusion
The `try` and `except` blocks in Python help you gracefully handle errors, while the `else` and `finally` blocks provide more control over your code’s flow. Here’s a quick recap of each component:
- **`try`**: Contains the code that might raise an exception.
- **`except`**: Catches and handles specific exceptions, letting you respond to errors.
- **`else`**: Runs if no exceptions occur, useful for actions that rely on the success of `try`.
- **`finally`**: Runs regardless of success or failure, ideal for cleanup actions.
Mastering `try`, `except`, `else`, and `finally` will help you write Python code that’s resilient and easier to troubleshoot, improving the overall quality of your programs.
Want to advance your Python programming skills? Enroll in our Python course by clicking the link below:
[Free Course: Python 3 for Beginners Python is one of the most used programming languages in the world. Both the popularity and the deman… 50 Lessons 1 Quizzes 1 Labs 5 Hr](https://www.serveracademy.com/courses/python-3-for-beginners/)
Now that you know the basics, try incorporating `try` and `except` in your own projects to see how it simplifies error handling and keeps your code running smoothly.
## CREATE YOUR FREE ACCOUNT & GET OUR
## FREE IT LABS
Create a free account
Next
Give me the course\!
Posted in [Coding and Automation](https://serveracademy.com/category/learning-path/coding-and-automation/), [Python](https://serveracademy.com/category/environment/python/)

### Paul Hill
Paul Hill is the founder of ServerAcademy.com and IT instructor to over 500,000 students online\!
## Posts navigation
[← Python Range() Tutorial for Beginners](https://serveracademy.com/blog/python-range-tutorial-for-beginners/)
[Python Interview Questions →](https://serveracademy.com/blog/python-interview-questions/)

We provide hands-on IT experience for current and aspiring IT professionals.
## Training
## [Sign Up Free](https://serveracademy.com/register "Sign Up Free")
## [Our Curriculum](https://serveracademy.com/curriculum "Our Curriculum")
## [IT Labs](https://serveracademy.com/it-labs "IT Labs")
## [Lab Challenges](https://serveracademy.com/lab-challenges/ "Lab Challenges")
## [Blog](https://serveracademy.com/blog "Blog")
## Members
## [Login](https://serveracademy.com/login "Login")
## [Community](https://community.serveracademy.com/ "Community")
## [Discord](https://discord.gg/w9BFAzNTYC "Discord")
## About Us
## [Contact](https://serveracademy.com/contact "Contact")
[Terms of Service](https://serveracademy.com/terms-of-service/) \| P[rivacy Policy](https://serveracademy.com/privacy-policy)
© 2024 ServerAcademy.com
This site is protected by reCAPTCHA and the Google
[Privacy Policy](https://policies.google.com/privacy) and
[Terms of Service](https://policies.google.com/terms) apply. |
| Readable Markdown | When writing Python code, errors can be frustrating. Luckily, Python’s `try` and `except` blocks provide an effective way to manage errors without breaking the flow of your code. The `try` and `except` statements let you handle specific exceptions, print error messages, and even use `else` and `finally` blocks for more control.
In this guide, we’ll explore how to use `try`, `except`, `else`, and `finally` effectively to write robust and error-tolerant Python code.
## What Is `try` and `except` in Python?
In Python, `try` and `except` are used to catch and handle exceptions, allowing your program to continue executing or provide custom error messages rather than crashing. Here’s a basic syntax for using `try` and `except`:
```
try:
# Code that might raise an exception
except SomeException:
# Code to run if the exception occurs
```
### Example Usage
Let’s look at a simple example to handle division by zero:
```
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
```
Output:
```
Cannot divide by zero!
```
In this example, the `try` block contains code that could potentially raise a `ZeroDivisionError`. When this error occurs, the code in the `except` block runs, printing a helpful message.
## Catching Specific Exceptions in Python
In Python, you can catch specific exceptions to handle different error types individually. This allows you to create custom responses for each error type and manage multiple errors gracefully.
```
try:
value = int("abc")
except ValueError:
print("Invalid number format!")
except TypeError:
print("Unsupported operation!")
```
Output:
```
Invalid number format!
```
Here, `try` and `except` are used to handle a `ValueError` (raised by trying to convert a string to an integer) with a custom error message. You can add as many specific `except` blocks as needed.
## Using `try` and `except` with `else`
In Python, the `else` block is used with `try` and `except` to define code that runs only if no exceptions occur in the `try` block. This is helpful when you want to perform certain actions only when the code in the `try` block is successful.
```
try:
number = int("42")
except ValueError:
print("Conversion failed!")
else:
print("Conversion successful:", number)
```
Output:
```
Conversion successful: 42
```
In this example, `else` only runs if the `try` block completes without error. If an exception occurs, the `else` block is skipped.
## Printing Errors in Python Try Except
Sometimes, you want to print the exact error message rather than a generic one. Python’s `except` block allows you to capture the error message using the `as` keyword.
```
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error occurred: {e}")
```
Output:
```
Error occurred: division by zero
```
By using `as e`, you can access the exception message, which provides specific details about the error that occurred.
## Using `try`, `except`, and `finally` in Python
The `finally` block runs regardless of whether an exception occurs or not. This is useful for cleanup tasks, such as closing files or releasing resources, that need to happen regardless of success or failure.
```
try:
file = open("sample.txt", "r")
data = file.read()
except FileNotFoundError:
print("File not found!")
finally:
file.close()
print("File closed.")
```
Output:
```
File not found!
File closed.
```
In this example, the `finally` block closes the file, ensuring the resource is released even if an error occurs. The `finally` block is a helpful way to maintain resource integrity in your programs.
## Practical Examples of Using `try`, `except`, `else`, and `finally`
### Example 1: Handling Multiple Exceptions
Here’s an example of using `try`, `except`, `else`, and `finally` to handle multiple exceptions in a single block:
```
try:
number = int(input("Enter a number: "))
result = 10 / number
except ValueError:
print("Invalid input! Please enter a numeric value.")
except ZeroDivisionError:
print("You cannot divide by zero!")
else:
print("Division successful! Result is:", result)
finally:
print("Program execution completed.")
```
Output if the user enters “0”:
```
You cannot divide by zero!
Program execution completed.
```
Output if the user enters “abc”:
```
Invalid input! Please enter a numeric value.
Program execution completed.
```
In this example:
- **`try`** contains code that could raise a `ValueError` or `ZeroDivisionError`.
- **`except`** catches these errors separately and provides specific error messages.
- **`else`** only runs if no exception occurs, and **`finally`** always runs, printing a completion message.
### Example 2: Using `try`, `except`, and `finally` with Resource Management
When working with files, databases, or network connections, `try`, `except`, and `finally` are invaluable for ensuring resources are properly closed, even if errors occur.
```
try:
with open("data.txt", "r") as file:
data = file.read()
except FileNotFoundError as e:
print(f"Error: {e}")
else:
print("File content successfully read!")
finally:
print("Resource handling complete.")
```
Output:
```
Error: [Errno 2] No such file or directory: 'data.txt'
Resource handling complete.
```
Using `with open` automatically closes the file after reading, but the `finally` block provides a good spot for additional cleanup or logging.
## Conclusion
The `try` and `except` blocks in Python help you gracefully handle errors, while the `else` and `finally` blocks provide more control over your code’s flow. Here’s a quick recap of each component:
- **`try`**: Contains the code that might raise an exception.
- **`except`**: Catches and handles specific exceptions, letting you respond to errors.
- **`else`**: Runs if no exceptions occur, useful for actions that rely on the success of `try`.
- **`finally`**: Runs regardless of success or failure, ideal for cleanup actions.
Mastering `try`, `except`, `else`, and `finally` will help you write Python code that’s resilient and easier to troubleshoot, improving the overall quality of your programs.
Want to advance your Python programming skills? Enroll in our Python course by clicking the link below:
[Free Course: Python 3 for Beginners Python is one of the most used programming languages in the world. Both the popularity and the deman… 50 Lessons 1 Quizzes 1 Labs 5 Hr](https://www.serveracademy.com/courses/python-3-for-beginners/)
Now that you know the basics, try incorporating `try` and `except` in your own projects to see how it simplifies error handling and keeps your code running smoothly. |
| Shard | 72 (laksa) |
| Root Hash | 12719377437839536672 |
| Unparsed URL | com,serveracademy!/blog/python-try-except/ s443 |