03 Oct Exception Handling
LAB 1: Write a Python function divide_numbers(num1, num) that takes two numbers as input and returns their division. If the second number is zero, raise a ZeroDivisionError and handle it by returning the message “Error: Division by zero is not allowed." Constraint num and num2 are integers between -100 and 100. You must handle the ZeroDivisionError explicitly.
def divide_numbers(num1, num2):
try:
result = num1 / num2
except ZeroDivisionError:
return "Error: Division by Zero is not allowed."
return result
print(divide_numbers(10, 2))
print(divide_numbers(10, 0))
LAB2: | Write a Python function get valid_number() that prompts the user to input a number and returns the integer value. | If the user provides a non-integer input, raise a ValueError and handle it by returning the ~~ message "Error: That's not a valid number." | | | Constraint | | The input should be a string that can be converted to an integer. | You must handle the ValueError explicitly. | | |
def get_valid_number():
try:
user_input = input("Enter a number: ")
number = int(user_input)
return number
except ValueError:
return "Error: That's not a valid number."
print(get_valid_number())
LAB3: Write a Python function safe_list_access(my_list, index) that takes a list my_list and an integer | index as input and returns the element at the given index. | If the index is out of range, raise an IndexError and handle it by returning the message "Error: Index out of range.” | Constraint | my _list will contain at least 1 integer and at most 200 integers. | index is an integer that can be any value (positive or negative). |
def safe_list_access(my_list, index):
try:
return my_list[index]
except IndexError:
return "Error: Index out of range"
my_list = [1, 2, 3, 4, 5]
print(safe_list_access(my_list, 2))
print(safe_list_access(my_list, 10))
print(safe_list_access(my_list, -3))
LAB 4: Write a Python function check positive(number) that takes an integer number as input. | | If the number is negative, raise a ValueError with the message "Negative numbers are not | allowed!" and handle it by returning the message. Otherwise, return the number. | | | Constraint | | The input number will be an integer between -100 and 100. | |
def check_positive(number):
if number < 0 :
raise ValueError ("Negative numbers are not allowed!")
return number
try:
print(check_positive(10))
print(check_positive(-5))
except ValueError as e:
print(e)
LAB 5: Write a Python function process_input(data) that takes a string data as input and performs the following actions: 1. If the string is empty, return the message “Error: Empty input provided.". 2.1f the string exceeds 255 characters, return the message “Error: Input exceeds maximum length.". 3. If the string contains any numeric characters, return the message “Error: Input contains invalid characters.". 4.1f none of the above conditions apply, return the message “Input processed successfully.". 5\ Program should handle all above scenarios by raising a CustomError Finally, ensure the message “Program execution completed.” is always printed. Constraint data is a string with a maximum length of 255 characters.
class CustomError(Exception):
"""Custom exception class for handling specific input errors."""
pass
def process_input(data: str) -> str:
try:
# Check if the input string is empty
if not data:
raise CustomError("Error: Empty input provided.")
# Check if the input string exceeds 255 characters
if len(data) > 255:
raise CustomError("Error: Input exceeds maximum length.")
# Check if the input string contains any numeric characters
if any(char.isdigit() for char in data):
raise CustomError("Error: Input contains invalid characters.")
# If none of the above conditions apply
return "Input processed successfully."
except CustomError as ce:
return str(ce) # Return the error message
finally:
# This block will execute regardless of what happens in the try block
print("Program execution completed.")
# Example usage
if __name__ == "__main__":
print(process_input("")) # Output: Error: Empty input provided.
print(process_input("A valid input string")) # Output: Input processed successfully.
print(process_input("A" * 256)) # Output: Error: Input exceeds maximum length.
print(process_input("Invalid123"))
.png)