Exploring Multithreading, API Requests, File Management and Exception Handling
As I continued learning, I was introduced to concepts that are commonly used in real-world applications, including multithreading, making API requests, working with the operating system and exception handling in Python.
What is Multithreading?
Normally, Python executes code sequentially, meaning one task is completed before the next one starts. However, with multithreading, multiple tasks can run concurrently.
Python provides the ThreadPoolExecutor class from the concurrent.futures module to execute tasks concurrently.
Using map() method we can run the same function on multiple inputs and automatically manages thread creation.
The submit() method submits tasks one by one and returns a future object.
API Requests
Pythons requests library makes sending HTTP requests simple. Many modern applications communicate with external services using APIs.
import requests
response = requests.get("https://....")
print(response.status_code)
#to retrieve the JSON data
data = response.json()
print(data)OS Module
This is use for interacting with Operating System.
os.makedirs(“File1”) — — — → Creates a new folder called File1.
Get Kavisha Nethmini’s stories in your inbox
Join Medium for free to get updates from this writer.
os.rmdir(“File1”) — — — → Remove the specified directory if it is empty.
print(os.path.abspath(“example.txt”)) — — — → Getting the absolute path of a file
Exception Handling in Python
While writing programs, errors are unavoidable. If an error occurs and we don’t handle it, the program immediately stops executing. Python provides Exception Handling to catch these errors so that rest of the program can continue running.
try-except
The try block contains the code that may cause an error. If an exception occurs, the except block handles it.
finally block
It always executes whether an exception occurs or not and it use for cleanup tasks such as closing files or database connections.
Getting actual error
Instead of printing a generic message, we can see the exact exception using except Exception as e:
def my_func(num):
print("Hello")
try:
if num % 2 == 0:
return 1
except Exception as e:
return e
finally:
print("I run always")
my_func(4)Own Exceptions
Python allows us to create our own exceptions using raise.
x = 99
if x < 100:
raise ValueError("Value less than 100 is not allowed")




