Advertisement
GamerBhai02

APP Exp 9

May 15th, 2025
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.67 KB | Source Code | 0 0
  1. def divide_numbers(a,b):
  2.     try:
  3.         result=a/b
  4.         return result
  5.     except ZeroDivisionError:
  6.         print("Error: Division by zero is not allowed.")
  7.         return None
  8.     except TypeError:
  9.         print("Error: Invalid data type. Please enter only numbers.")
  10.         return None
  11.     finally:
  12.         print("Execution of divide_numbers() completed.")
  13.        
  14. def access_list_element(lst,index):
  15.     try:
  16.         return lst[index]
  17.     except IndexError:
  18.         print(f"Error: Index {index} out of range.")
  19.         return None
  20.  
  21. def convert_to_int(value):
  22.     try:
  23.         return int(value)
  24.     except ValueError:
  25.         print(f'Error: Could not convert {value} to an integer.')
  26.         return None
  27.  
  28. def ExElseBlock(value):
  29.     try:
  30.         num = int(value)
  31.     except ValueError:
  32.         print("Conversion failed.")
  33.     else:
  34.         print(f'Conversion Successful: {num}')
  35.     finally:
  36.         print("Execution of ExElseBlock completed.")
  37.        
  38. if __name__ == "__main__":
  39.     print("--- Handling ZeroDivisionError ---")
  40.     divide_numbers(10,0)
  41.    
  42.     print("\n--- Handling TypeError ---")
  43.     divide_numbers(10,"two")
  44.    
  45.     print("\n--- Division without any error ---")
  46.     print(divide_numbers(10,2))
  47.    
  48.     print("\n--- Handling IndexError ---")
  49.     my_list = [1,2,3]
  50.     access_list_element(my_list,5)
  51.    
  52.     print("\n--- Handling ValueError ---")
  53.     convert_to_int("abc")
  54.    
  55.     print("\n--- No ValueError ---")
  56.     print(convert_to_int(34.78))
  57.    
  58.     print("\n--- Handling Exception with else block ---")
  59.     ExElseBlock("100")
  60.    
  61.     print("\n--- Handling Exception with else block ---")
  62.     ExElseBlock("abc")
Tags: Exp 9
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement