Today, we're continuing our 10-day journey to learn Python, kicking off Day 8's lesson. If you haven't checked out Day 1 yet, you can find it here: 🎁Learn Python in 10 Days: Day 1
Day 8: Exceptions
1. Understanding Exceptions
When the Python interpreter detects an error, it can't execute the code and instead displays an error message. This is called an "exception," or more commonly, a "bug."
Historically, a literal bug (insect) caused a malfunction in a computer, so we now refer to software errors as "bugs."
Example: Trying to open a non-existent file.
f = open("www.txt", "r", encoding="utf-8")
# FileNotFoundError: [Errno 2] No such file or directory: 'www.txt'
2. Handling Exceptions
Handling exceptions means preparing for and dealing with potential errors to avoid program crashes.
Reasons to catch exceptions:
- Improve Stability: Prevent your program from crashing due to errors.
- Easier Debugging: Get detailed error info to quickly locate issues.
- Better Maintenance: Separate error-handling code from business logic.
When encountering a bug, you can either:
- Stop the entire program,
- Handle the bug and continue running.
In practice, it's better to handle errors so that your program can continue running smoothly.
Basic syntax for catching exceptions:
try:
# Code that may raise an error
except:
# Code to run if an error occurs
Example: Try opening a file in read mode, if it doesn't exist, open it in write mode.
try:
f = open("www.txt", "r", encoding="utf-8")
except:
f = open("www.txt", "w", encoding="utf-8")
Catching specific exceptions:
try:
print(name)
except NameError as e:
print("NameError: 'name' is not defined")
Important Notes:
- If the error type doesn't match the one you're catching, the exception won't be caught.
- Generally, put only one line of code in the
try
block.
Catching multiple exceptions:
try:
print(1 / 0)
except (NameError, ZeroDivisionError):
print("Error occurred")
Catching all exceptions:
try:
# Code that may raise an error
except Exception as e:
# Code to run if any error occurs
Using else
: Code that runs if no exceptions occur.
try:
print(1)
except Exception as e:
print(e)
else:
print("No exceptions occurred")
Using finally
: Code that runs no matter what.
try:
f = open("test.txt", "r", encoding="utf-8")
except Exception as e:
print(e)
f = open("test.txt", "w", encoding="utf-8")
else:
print("No exceptions occurred")
finally:
f.close()
3. Exception Propagation
def func1():
print("Start of func1")
print(1 / 0)
print("End of func1")
def func2():
print("Start of func2")
func1()
print("End of func2")
def main():
try:
func2()
except Exception as e:
print(e)
main()
# Output:
# Start of func2
# Start of func1
# division by zero
If an exception isn't caught within a function, it propagates to the calling function.
4. Python Modules
A Python module is a file ending in .py
. It can define functions, classes, and variables, and can also include executable code.
Modules help bundle related functions and data. For instance, use the time
module for time-related tasks.
Importing modules:
import time
print("Start")
time.sleep(1)
print("End")
Using from
to import specific attributes:
from time import sleep
print("Start")
sleep(1)
print("End")
Using *
to import all attributes:
from time import *
sleep(1)
Using as
to create aliases:
import time as t
t.sleep(2)
print("haha")
from time import sleep as sl
sl(2)
print("hehe")
4.2 Creating Custom Modules
You can create your own modules for specific tasks by writing Python files.
Example: Create my_module.py
with a function:
# my_module.py
def my_test(a, b):
print(a + b)
if __name__ == '__main__':
my_test(1, 2)
# another_module.py
from my_module import my_test
my_test(1, 2)
5. Python Packages
A package is a collection of modules. Physically, it's a folder containing a special __init__.py
file.
Creating a package:
- Create a folder named
my_package
. - Add modules (
my_module1.py
,my_module2.py
). - Add an
__init__.py
file.
Using packages:
import my_package.my_module1
my_package.my_module1.my_function()
Or using from
import:
from my_package import my_module1
my_module1.my_function()
5.2 Installing Third-Party Packages
Use pip
to install third-party packages:
pip install package_name
To speed up the process by using a mirror site:
pip install -i https://packagecloud.io/pypa/python/simple package_name
Example: Creating a custom package my_utils
.
- Create a folder
my_utils
. - Add
str_util.py
andfile_util.py
.
# str_util.py
def str_reverse(s):
return s[::-1]
def substr(s, x, y):
return s[s.index(x):s.index(y)]
# file_util.py
def print_file_info(file_name):
try:
with open(file_name, 'r') as f:
content = f.read()
print(content)
except Exception as e:
print(e)
def append_file_info(file_name, data):
with open(file_name, 'a') as f:
f.write(data + "\n")
Then use these modules in your scripts:
from my_utils import str_util, file_util
print(str_util.str_reverse("hello"))
file_util.append_file_info("test.txt", "Some data")
By following these guidelines, you can effectively handle exceptions, organize your code with modules and packages, and utilize third-party libraries to enhance your Python projects.
Top comments (0)