diff --git a/2024/tuesday_tips/custom_exceptions/basic_example.py b/2024/tuesday_tips/custom_exceptions/basic_example.py new file mode 100644 index 00000000..6fc30346 --- /dev/null +++ b/2024/tuesday_tips/custom_exceptions/basic_example.py @@ -0,0 +1,25 @@ +class Person: + def __init__(self, name: str): + self.name: str = name + self._age: int + + @property + def age(self): + return self._age + + @age.setter + def age(self, value: int): + if value < 0: + raise ValueError("Age cannot be negative") + self._age = value + +def main() -> None: + try: + person = Person("John") + person.age = -10 + print(f"Name: {person.name}, age: {person.age}") + except ValueError as error: + print(f"Error occurred: {error}") + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/2024/tuesday_tips/custom_exceptions/custom_exceptions.py b/2024/tuesday_tips/custom_exceptions/custom_exceptions.py new file mode 100644 index 00000000..fb90a8d6 --- /dev/null +++ b/2024/tuesday_tips/custom_exceptions/custom_exceptions.py @@ -0,0 +1,48 @@ +class WeightLimitExceededError(Exception): + """Raised when the weight limit of a container is exceeded.""" + + def __init__(self, limit: int, current: int): + super().__init__(f"Weight limit exceeded: limit= {limit}, current= {current}") + self.limit = limit + self.current = current + + +class WeightNegativeError(Exception): + """Raised when the weight of an item is negative.""" + + def __init__(self, weight: int): + self.weight = weight + self.message = f"Weight cannot be negative: weight= {weight}" + + +class Container: + def __init__(self, limit: int): + self.limit = limit + self.current_weight = 0 + + def load_item(self, weight: int): + if weight < 0: + raise WeightNegativeError(weight) + + new_weight = self.current_weight + weight + + if new_weight > self.limit: + raise WeightLimitExceededError(self.limit, new_weight) + + self.current_weight = new_weight + print("Item loaded") + + +def main() -> None: + try: + container = Container(limit=100) + container.load_item(50) # This should work fine + container.load_item(-60) # This will raise a WeightLimitExceededError + except WeightLimitExceededError as e: + print(e) + except WeightNegativeError as e: + print(e.message) + + +if __name__ == "__main__": + main() diff --git a/2024/tuesday_tips/custom_exceptions/data.txt b/2024/tuesday_tips/custom_exceptions/data.txt new file mode 100644 index 00000000..3d793690 --- /dev/null +++ b/2024/tuesday_tips/custom_exceptions/data.txt @@ -0,0 +1,4 @@ +Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. +Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. +Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. \ No newline at end of file diff --git a/2024/tuesday_tips/custom_exceptions/else_clause_use_case.py b/2024/tuesday_tips/custom_exceptions/else_clause_use_case.py new file mode 100644 index 00000000..91526c75 --- /dev/null +++ b/2024/tuesday_tips/custom_exceptions/else_clause_use_case.py @@ -0,0 +1,17 @@ +def process(data: str) -> None: + print("Processing data") + + +def main() -> None: + file = None + try: + file = open("data.txt", "r") + data = file.read() + except IOError: + print("Error reading file") + else: + # Process the data + process(data) + finally: + if file is not None: + file.close() diff --git a/2024/tuesday_tips/custom_exceptions/exception_chaining.py b/2024/tuesday_tips/custom_exceptions/exception_chaining.py new file mode 100644 index 00000000..340f430f --- /dev/null +++ b/2024/tuesday_tips/custom_exceptions/exception_chaining.py @@ -0,0 +1,17 @@ +def convert_to_integer(text: str) -> int: + try: + return int(text) + except ValueError as e: + raise TypeError("Conversion to integer failed") from e + + +def main() -> None: + try: + print(convert_to_integer("abc")) + except Exception as e: + print(f"An error occurred: {e}") + print(f"Cause of the error: {e.__cause__}") + + +if __name__ == "__main__": + main() diff --git a/2024/tuesday_tips/custom_exceptions/exception_with_custom_data.py b/2024/tuesday_tips/custom_exceptions/exception_with_custom_data.py new file mode 100644 index 00000000..1fe10c89 --- /dev/null +++ b/2024/tuesday_tips/custom_exceptions/exception_with_custom_data.py @@ -0,0 +1,16 @@ +class CustomError(Exception): + def __init__(self, message: str, extra_data: dict[str, str]): + super().__init__(message) + self.extra_data = extra_data + + +def main() -> None: + try: + raise CustomError("An error occurred", {"key": "value"}) + except CustomError as e: + print(e) + print(e.extra_data) # Prints: {'key': 'value'} + + +if __name__ == "__main__": + main() diff --git a/2024/tuesday_tips/custom_exceptions/how_to_use_exceptions.py b/2024/tuesday_tips/custom_exceptions/how_to_use_exceptions.py new file mode 100644 index 00000000..355c8005 --- /dev/null +++ b/2024/tuesday_tips/custom_exceptions/how_to_use_exceptions.py @@ -0,0 +1,27 @@ +class CarNotAvailableException(Exception): + pass + + +def rent_car(car_type: str, days: int) -> int: + available_cars = ["sedan", "SUV", "hatchback"] + if car_type not in available_cars: + raise CarNotAvailableException(f"{car_type} is not available.") + + # Calculate rental cost, etc. + rental_cost = days * 40 # Assume a fixed rate per day + return rental_cost + + +def main() -> None: + try: + rent_car("SUB", 5) + print("Car rented successfully.") + except CarNotAvailableException as e: + print(e) + print("Please choose a different car type.") + finally: + print("Thank you for using our car rental service.") + + +if __name__ == "__main__": + main() diff --git a/2024/tuesday_tips/custom_exceptions/pyproject.toml b/2024/tuesday_tips/custom_exceptions/pyproject.toml new file mode 100644 index 00000000..d70ec287 --- /dev/null +++ b/2024/tuesday_tips/custom_exceptions/pyproject.toml @@ -0,0 +1,15 @@ +[tool.poetry] +name = "custom-exceptions" +version = "0.1.0" +description = "" +authors = ["Andreas Bergman "] +license = "MIT" +readme = "README.md" + +[tool.poetry.dependencies] +python = "^3.12" + + +[build-system] +requires = ["poetry-core"] +build-backend = "poetry.core.masonry.api"