Free Online Code Editor
Catch and handle exceptions gracefully.
# Error handling in Python
def safe_divide(a, b):
try:
result = a / b
except ZeroDivisionError:
return "Error: Cannot divide by zero!"
except TypeError:
return "Error: Invalid types!"
else:
return f"Result: {result}"
finally:
print(f" [Attempted: {a} / {b}]")
print(safe_divide(10, 3))
print(safe_divide(10, 0))
# Custom exceptions
class ValidationError(Exception):
def __init__(self, field, message):
self.field = field
self.message = message
super().__init__(f"{field}: {message}")
try:
raise ValidationError("email", "Invalid format")
except ValidationError as e:
print(f"\nValidation failed - {e.field}: {e.message}")Use try/except/else/finally for error handling. Create custom exceptions by inheriting from Exception.