summaryrefslogtreecommitdiff
path: root/py02/ex3/ft_custom_errors.py
blob: 57d5a4739d6f0a8fb21c4e580993bc7fccb93734 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#!/usr/bin/env python3

class GardenError(Exception):
    def __init__(self, message="Unknown plant error"):
        self.message = message
        # Why self.message; why not just 'message'
        super().__init__(self.message)


class PlantError(GardenError):
    pass


class WaterError(GardenError):
    pass


def test_plant_error(veg_item):
    if veg_item not in veg_list:
        raise PlantError(f"The {veg_item} is not in the list!")
    else:
        print("The vegetale is in the list")


def test_water_error(level):
    if level < 10:
        raise WaterError("Not enough water in the tank!")
    else:
        print("We have enough water!")


def main():
    print("== Custom Garden Errors Demo")
    print()
    try:
        print("Testing PlantError...")
        test_plant_error("spinach")
    except PlantError as err:
        print("Caught PlantError:", err)
        print()
    try:
        print("Testing WaterError...")
        test_water_error(4)
    except WaterError as err:
        print("Caught WaterError:", err)
    try:
        print()
        print("Testing catching all garden errors...")
        test_plant_error("spinach")
    except GardenError as err:
        print("Caught GardenError:", err)
    try:
        test_water_error(4)
    except GardenError as err:
        print("Caught GardenError:", err)
    finally:
        print()
        print("All custom error types work correctly!")


if __name__ == "__main__":
    veg_list = ["carrot", "fennel", "sesame"]
    main()