π™π™£π™§π™šπ™–π™‘ π˜Ύπ™€π™™π™šπ™§
1.52K subscribers
6 photos
7 files
34 links
A place for coders ;)
Download Telegram
#python

How to handle error with exception in python

Python has try and except keywords it is similar as try catch and used to handle error.

Example code:


try:
# Code that may raise an exception or trigger an error

# Example 1: Raising a custom exception
if some_condition:
raise Exception("Custom exception message")

# Example 2: Triggering a specific error
if another_condition:
raise ValueError("Custom error message")

# Example 3: Catching and handling specific exception types
if yet_another_condition:
raise IndexError("Invalid index")

# Other code statements...

except Exception as e:
# Handle generic exceptions
print("Caught exception:", str(e))
except ValueError as ve:
# Handle specific exception types
print("Caught ValueError:", str(ve))
except IndexError as ie:
# Handle specific exception types
print("Caught IndexError:", str(ie))
#python
Basic Threading Example - Run your code in parallel

import threading
def sum(x, y):
result = x + y
print(f"The sum of {x} and {y} is {result}")

# Number of iterations num_iterations = 50

# Loop to create and start threads

for i in range(num_iterations):

thread = threading.Thread(target=sum, args=(3, 5))

# Start the thread

thread.start()

# Wait for all threads to finish

thread.join()

print("Program completed.")


Usage:
target= which function do u want to run on thread

args= the required params of targeted function
πŸ‘7❀1