Write a Python program that reads a configuration file and raises custom exceptions with descriptive messages if required configuration keys are missing.
Example 1:
Input: File contents: {"username": "user1", "password": "password1"}
Output: "Error: Missing key: 'server'."
Example 2:
Input: File contents: {"username": "user1", "password": "password1", "server": "localhost"}
Output: "Configuration file checked successfully."
Use the json module to read the configuration file.
import json
def check_config(file):
required_keys = ["username", "password", "server"]
with open(file, 'r') as f:
config = json.load(f)
for key in required_keys:
if key not in config:
raise Exception(f"Error: Missing key: '{key}'.")
return "Configuration file checked successfully."
print(check_config("config1.json")) # Output: "Error: Missing key: 'server'."
print(check_config("config2.json")) # Output: "Configuration file checked successfully."
Unlock AI & Data Science treasures. Log in!