59 lines
1.5 kB
1class GardenError(Exception):
2 def __init__(self, message: str = "Unknown garden error") -> None:
3 super().__init__(message)
4
5
6class PlantError(GardenError):
7 def __init__(self, message: str = "Unknown plant error") -> None:
8 super().__init__(message)
9
10
11class WaterError(GardenError):
12 def __init__(self, message: str = "Unknown water error") -> None:
13 super().__init__(message)
14
15
16def check_plant(plant_status: str) -> None:
17 if plant_status == "wilting":
18 raise PlantError("The tomato plant is wilting!")
19
20
21def check_water(water_level: int) -> None:
22 if water_level < 10:
23 raise WaterError("Not enough water in the tank!")
24
25
26def test_custom_errors() -> None:
27 print("=== Custom Garden Errors Demo ===\n")
28
29 print("Testing PlantError...")
30 try:
31 check_plant("wilting")
32 except PlantError as error:
33 print(f"Caught PlantError: {error}")
34
35 print()
36
37 print("Testing WaterError...")
38 try:
39 check_water(5)
40 except WaterError as error:
41 print(f"Caught WaterError: {error}")
42
43 print()
44
45 print("Testing catching all garden errors...")
46 for test in [0, 1]:
47 try:
48 if test == 0:
49 check_plant("wilting")
50 else:
51 check_water(5)
52
53 except GardenError as error:
54 print(f"Caught GardenError: {error}")
55 print("\nAll custom error types work correctly!")
56
57
58if __name__ == "__main__":
59 test_custom_errors()