🛡️

How to Handle Errors in Python

PythonIntermediate

Catch and handle exceptions gracefully.

Code Example

Python
# 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}")

Explanation

Use try/except/else/finally for error handling. Create custom exceptions by inheriting from Exception.

Related Tutorials