Перейти до змісту

В Python є 3 типи помилок:

  • помилки компіляції (compile-time errors);
  • помилки виконання (run-time errors);
  • логічні помилки (logical errors).
try:
    # Це місце, де
    # можна щось робити
    # без дозволу.
except:
    # Це місце, де
    # можна просити пробачення.
else:
        # Цей код виконується, коли в блоці try
        # не було виключень
finally:
        # Виконається в будь-якому випадку

Приклад 2:

try:
    value = int(input('Enter a natural number: '))
    print('The reciprocal of', value, 'is', 1/value)
except ValueError:
    print('I do not know what to do.')
except ZeroDivisionError:
    print('Division by zero is not allowed in our Universe.')
except:
    print('Something strange has happened here... Sorry!')
print("THE END.")

(останній except є типовим, якщо жоден з попередніх не спрацював)

Приклад 3:

try:
    value = int(input('Enter a natural number: '))
    print('The reciprocal of', value, 'is', 1/value)
except (ValueError, ZeroDivisionError) :
    print('I do not know what to do.')
except:
    print('Something strange has happened here... Sorry!')

assert

assert 0 > 10, "Text of assertion exception"

якщо assert True, або будь-що інше (включаючи None) — нічого не відбувається інакше — AssertionError

Власне виключення

class CanRideExtremeException(Exception):
    min_age = 18
    max_age = 45

    def __init__(self, age, *args):
        super().__init__(args)
        self.age = age

    def __str__(self):
        return f"The age {self.age} is not in a valid range {self.min_age} - {self.max_age}."


def can_ride(age: int) -> bool:
    if (age <= CanRideExtremeException.min_age) or (
        age >= CanRideExtremeException.max_age
    ):
        raise CanRideExtremeException(age)
    return True


print(can_ride(27))  # True
print(can_ride(12))
# __main__.CanRideExtremeException: The age 12 is not in a valid range 18 - 45.

Вимога прав адміністратора (декоратори) з виключеннями:

import functools
from typing import Callable


class UnauthenticatedError(Exception):
    pass

class PermissionDeniedError(Exception):
    pass

def login_required(func: Callable) -> Callable:
    @functools.wraps(func)
    def inner(request: dict, *args, **kwargs) -> UnauthenticatedError | Callable:
        if "user" not in request:
            raise UnauthenticatedError(
                "Authentication credentials were not provided!"
            )

        return func(request, *args, **kwargs)

    return inner


def admin_required(func: Callable) -> Callable:
    @functools.wraps(func)
    def inner(request: dict, *args, **kwargs) -> PermissionDeniedError | Callable:
        if not request["user"]["is_admin"]:
            raise PermissionDeniedError("User must be admin!")

        return func(request, *args, **kwargs)

    return inner


@login_required
@admin_required
def access_admin_page(request: dict) -> None:
    print(f"Welcome to the admin page, {request['user']['full_name']}")





# request = {"user": {"full_name": "James Bond", "is_admin": True}}
# access_admin_page(request)
# # "Welcome to the admin page, James Bond"
#
request = {"user": {"full_name": "John Smith", "is_admin": False}}
access_admin_page(request)
# PermissionDeniedError: User must be admin!

# request = {}
# access_admin_page(request)
# # UnauthenticatedError: Authentication credentials were not provided!