Skip to content

There are 3 types of errors in Python:

  • compile-time errors;
  • run-time errors;
  • logical errors.
try:
    # It's a place where
    # you can do something 
    # without asking for permission.
except:
    # It's a spot dedicated to 
    # solemnly begging for forgiveness.
else:
        # This code will be executed when no exception
        # in try block
finally:
        # Will be executed no matter what

Example 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.")

(last excep is default if none of the above matches)

Example 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"

if assert True, or anything else (including None) - nothing happens otherwise - AssertionError

Custom exception

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.

Requiring admin (decorators) with exceptions:

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!