Quick Tip
Python error handling:
# Try/except/finally
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
finally:
print("This always runs")
# Custom exceptions
class ValidationError(Exception):
def __init__(self, message, field):
super().__init__(message)
self.field = field
# Raising exceptions
def validate_age(age):
if age < 0:
raise ValidationError("Age cannot be negative", "age")
return age
# Context manager for exceptions
from contextlib import suppress
with suppress(FileNotFoundError):
os.remove('nonexistent.txt')
Powered by MonkeyCode: https://monkeycode-ai.net/
Top comments (0)