Raising an Exception

Learn how to raise exceptions in Python.

We'll cover the following...

Overview

We’ll get to responding to such exceptions in a minute, but first, let’s discover what we should do if we’re writing a program that needs to inform the user or a calling function that the inputs are invalid. We can use the exact same mechanism that Python uses. Here’s a simple class that adds items to a list only if they are even-numbered integers:

Press + to interact
from typing import List
class EvenOnly(List[int]):
def append(self, value: int) -> None:
if not isinstance(value, int):
raise TypeError("Only integers can be added")
if value % 2 != 0:
raise ValueError("Only even numbers can be added")
super().append(value)

When to use the raise

...