shield-halvedBài tập Exception Handling - Nâng cao

Các bài tập về Exception Handling - Nâng cao

  1. Viết class InvalidAgeError (custom exception) để validate tuổi (phải từ 0-150).

class InvalidAgeError(Exception):
    pass

def validate_age(age):
    # Code của bạn ở đây
    pass

# Test
try:
    validate_age(-5)
except InvalidAgeError as e:
    print(f"Lỗi: {e}")
  1. Viết decorator exception_handler tự động bắt và log exception.

def exception_handler(func):
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            print(f"Error in {func.__name__}: {e}")
            return None
    return wrapper

@exception_handler
def divide(a, b):
    return a / b

# Test
print(divide(10, 2))  # 5.0
print(divide(10, 0))  # Error message, returns None
  1. Viết context manager class FileHandler tự động đóng file kể cả khi có lỗi.

  1. Viết hàm retry_on_exception thử lại operation n lần khi gặp exception.

  1. Viết hàm safe_chain_operations thực hiện nhiều operations, dừng và rollback khi có lỗi.

  1. Viết class ValidationError với nhiều loại validation khác nhau.

  1. Viết hàm exception_context_manager sử dụng contextlib để tạo context manager.

  1. Viết hàm aggregate_exceptions thu thập tất cả exceptions từ nhiều operations.

  1. Viết ExceptionLogger class ghi log chi tiết exceptions (timestamp, traceback, context).

  1. Viết hàm timeout_operation thực thi operation với timeout, raise exception nếu quá thời gian.

  1. Viết ExceptionChain xử lý chuỗi exceptions với context.

  1. Viết hàm safe_parallel_execution chạy nhiều tasks song song, thu thập tất cả exceptions.

  1. Viết ResourceManager quản lý tài nguyên với proper cleanup kể cả khi có exception.

  1. Viết hàm exception_statistics thu thập thống kê về exceptions trong một khối code.

  1. Viết CircuitBreaker pattern để prevent cascading failures.

  1. Viết hàm exception_to_result chuyển exceptions thành Result type (Either monad).

  1. Viết ExceptionGroup (Python 3.11+) xử lý nhiều exceptions cùng lúc.

  1. Viết SmartRetry với exponential backoff và jitter.

  1. Viết TransactionManager với rollback support.

  1. Viết comprehensive ExceptionHandler middleware cho web applications.

Last updated