DEV Community

niuniu
niuniu

Posted on

Quick Tip: Python Error Handling

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')
Enter fullscreen mode Exit fullscreen mode

Powered by MonkeyCode: https://monkeycode-ai.net/

python #coding #tips

Top comments (0)