-
Notifications
You must be signed in to change notification settings - Fork 146
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge branch '2024_tt_custom_exceptions'
- Loading branch information
Showing
8 changed files
with
169 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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. |
17 changes: 17 additions & 0 deletions
17
2024/tuesday_tips/custom_exceptions/else_clause_use_case.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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() |
16 changes: 16 additions & 0 deletions
16
2024/tuesday_tips/custom_exceptions/exception_with_custom_data.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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() |
27 changes: 27 additions & 0 deletions
27
2024/tuesday_tips/custom_exceptions/how_to_use_exceptions.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
[tool.poetry] | ||
name = "custom-exceptions" | ||
version = "0.1.0" | ||
description = "" | ||
authors = ["Andreas Bergman <[email protected]>"] | ||
license = "MIT" | ||
readme = "README.md" | ||
|
||
[tool.poetry.dependencies] | ||
python = "^3.12" | ||
|
||
|
||
[build-system] | ||
requires = ["poetry-core"] | ||
build-backend = "poetry.core.masonry.api" |