Error and Exception Handling · 5 / 20 Theory

Raising exceptions and creating your own

Until now Python raised the exceptions. You can raise them too, to warn that something is not valid, and create your own types that describe the errors of your program.

raise: raising an exception

def square_root(x):
    if x < 0:
        raise ValueError("Negative number")
    return x ** 0.5

print(square_root(16))   # 4.0
print(square_root(-4))   # ValueError: Negative number

raise interrupts the function like a return, but instead of returning a value it sends the error up to whoever called the function, who can catch it:

try:
    print(square_root(-4))
except ValueError as error:
    print(f"Error: {error}")   # Error: Negative number

It is the scheme of Validated square root.

Why raise an exception instead of returning an error value

# With a special value: easy to ignore by accident
def root(x):
    if x < 0:
        return -1         # and what if -1 were a valid result?
    return x ** 0.5

# With an exception: it cannot be ignored
# if nobody catches it, the program stops and shows the error

An exception is not overlooked and is not confused with a valid result.

Re-raising: raise without arguments

Sometimes you want to do something when an error occurs (for example, log it) but let it keep going up. Inside the except, a bare raise re-raises the same exception:

try:
    int("abc")
except ValueError:
    print("Logging the error...")
    raise                      # the error continues on its way

Your own exceptions

They are created by inheriting from Exception. An empty class is enough, and you already have a type with its own name that can be caught:

class InsufficientFundsError(Exception):
    pass

def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientFundsError("Not enough money")
    return balance - amount

try:
    withdraw(50, 80)
except InsufficientFundsError as error:
    print(error)       # Not enough money

The name of custom exceptions ends by convention in Error.

With attributes and its own message

An exception is a class, so it can have a constructor and data. The Exception constructor is called with super().__init__ to set the message:

class InsufficientFundsError(Exception):
    def __init__(self, missing):
        super().__init__(f"Insufficient funds: missing {missing}")
        self.missing = missing

try:
    raise InsufficientFundsError(30)
except InsufficientFundsError as error:
    print(error)            # Insufficient funds: missing 30
    print(error.missing)    # 30

This way, whoever catches the error receives not only a text, but information they can use. It is the structure of Custom exception.

Your own hierarchies

class AccountError(Exception):
    pass

class InsufficientFundsError(AccountError):
    pass

class BlockedAccountError(AccountError):
    pass

try:
    raise BlockedAccountError("Account blocked")
except AccountError as error:      # catches either of the two
    print(error)

assert: internal checks

assert condition, message raises AssertionError if the condition is false. It is useful to check the programmer's assumptions during development, not to validate what the user types:

def average(numbers):
    assert len(numbers) > 0, "The list cannot be empty"
    return sum(numbers) / len(numbers)