Search⌘ K

Raising an Exception

Explore how to raise exceptions in Python by using the raise keyword to enforce input validation. Understand when to trigger built-in errors like TypeError and ValueError and how to apply these principles to maintain robust, error-resistant programs. This lesson helps you grasp how to inform users or calling functions about invalid inputs, improving program reliability.

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:

Python 3.10.4
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

...