09. Error Handling
Try/Except
def divide(a, b):
try:
result = a / b
return result
except ZeroDivisionError:
return 0
except TypeError:
return None
Catching Multiple Exceptions
try:
result = int(user_input) / divisor
except (ValueError, ZeroDivisionError) as e:
print(f"Error: {e}")
result = None
The Exception Object
try:
data = json.loads(invalid_json)
except json.JSONDecodeError as e:
print(f"Failed to parse JSON at position {e.pos}")
print(f"Error: {e.msg}")
Finally
try:
file = open("data.json")
data = json.load(file)
finally:
file.close() # Always runs
Or use with to avoid explicit close:
try:
with open("data.json") as f:
data = json.load(f)
except FileNotFoundError:
data = {}
Raising Errors
def call_api(model_name):
valid_models = ["gpt-4", "gpt-3.5-turbo", "claude-3"]
if model_name not in valid_models:
raise ValueError(f"Unknown model: {model_name}. Valid: {valid_models}")
# ... proceed with API call
Local verification checkpoint
Run the smallest example from this chapter in a local workspace and record the package version, runtime, data path, and observed output. If the result depends on model size, vector count, CPU/GPU backend, or available memory, note that constraint beside the exercise so the lesson remains reproducible.
Local verification checkpoint
Run the smallest example from this chapter in a local workspace and record the package version, runtime, data path, and observed output. If the result depends on model size, vector count, CPU/GPU backend, or available memory, note that constraint beside the exercise so the lesson remains reproducible.
Write a function parse_temperature that accepts a string input, converts it to float, and raises a ValueError if the value is outside 0.0 to 2.0. Handle the ValueError when calling the function with invalid input.