Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def divide_numbers(a,b):
- try:
- result=a/b
- return result
- except ZeroDivisionError:
- print("Error: Division by zero is not allowed.")
- return None
- except TypeError:
- print("Error: Invalid data type. Please enter only numbers.")
- return None
- finally:
- print("Execution of divide_numbers() completed.")
- def access_list_element(lst,index):
- try:
- return lst[index]
- except IndexError:
- print(f"Error: Index {index} out of range.")
- return None
- def convert_to_int(value):
- try:
- return int(value)
- except ValueError:
- print(f'Error: Could not convert {value} to an integer.')
- return None
- def ExElseBlock(value):
- try:
- num = int(value)
- except ValueError:
- print("Conversion failed.")
- else:
- print(f'Conversion Successful: {num}')
- finally:
- print("Execution of ExElseBlock completed.")
- if __name__ == "__main__":
- print("--- Handling ZeroDivisionError ---")
- divide_numbers(10,0)
- print("\n--- Handling TypeError ---")
- divide_numbers(10,"two")
- print("\n--- Division without any error ---")
- print(divide_numbers(10,2))
- print("\n--- Handling IndexError ---")
- my_list = [1,2,3]
- access_list_element(my_list,5)
- print("\n--- Handling ValueError ---")
- convert_to_int("abc")
- print("\n--- No ValueError ---")
- print(convert_to_int(34.78))
- print("\n--- Handling Exception with else block ---")
- ExElseBlock("100")
- print("\n--- Handling Exception with else block ---")
- ExElseBlock("abc")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement