01 / 20

Raising
Exceptions

Learn to intentionally raise exceptions in Python to guard against invalid states and write defensive, robust code.

Python

What Is an Exception?

An exception is a signal that something unexpected happened during program execution. Python stops the normal flow and looks for a handler. Common built-in exceptions include ValueError, TypeError, and ZeroDivisionError.

Catching vs Raising

Catching (try/except)
You react to an exception someone else raised. You handle the problem gracefully.
Raising (raise)
You create an exception yourself when you detect an invalid state in your own code.

Why Raise Exceptions?

1
Guard against bad input: Stop invalid data before it causes silent bugs downstream.
2
Communicate clearly: A descriptive error message tells the caller exactly what went wrong.
3
Fail fast: Crashing immediately on an impossible state is safer than producing garbage results.
4
Document contracts: Raising exceptions makes your function's requirements explicit and testable.

The raise Statement

raise ExceptionType ("message") keyword built-in class descriptive string
raise ValueError("Age cannot be negative")

Anatomy of a raise Statement

raise ValueError (
"Age must be \(\ge\) 0"
) Keyword Triggers the exception Exception Type Built-in or custom exception class Error Message Human-readable description Common Built-in Exception Types ValueError TypeError RuntimeError KeyError Wrong value Wrong type Logic error Missing key

raise vs return: Key Distinction

raise return
Purpose Signal an error Provide a result
Control flow Jumps to nearest except Returns to caller normally
Caller must Handle with try/except Store or use the value
When ignored Program crashes Value is silently lost
Best for Invalid / impossible states Normal results, including None

How to Apply: Step by Step

1
Identify the contract: What inputs are valid? What states are impossible?
2
Write a guard clause: Use an if statement to check the invalid condition early.
3
Choose the right exception type: ValueError for bad values, TypeError for bad types, etc.
4
Write a clear message: Include the parameter name and why it was rejected.
5
Place guards at the top: Validate before doing any real work so the function fails fast.

Example 1: Validating Age

def set_age(age): if age < 0: raise ValueError("age cannot be negative") return age
set_age(-5)
\(-5 < 0\)?
True raise! set_age(25)
\(25 < 0\)?
False return 25 ValueError: age cannot be negative Invalid input path Valid input path

Example 2: Multiple Guards

def divide(a, b): if not isinstance(b, (int, float)): raise TypeError("b must be a number") if b == 0: raise ValueError("b cannot be zero") return a / b

Example 3: User Registration

def register_user(username, email): if not username: raise ValueError("username cannot be empty") if "@" not in email: raise ValueError("email must contain @") if len(username) > 30: raise ValueError("username too long (max 30)") # ... proceed to create the account return {"user": username, "email": email}

The Guard Clause Pattern

Function called Guard 1: valid? raise No Yes Guard 2: valid? raise No Yes Guard 3: valid? raise No Yes Main logic runs Guard clauses filter invalid inputs

Choosing the Right Exception Type

ValueError
Right type, wrong value: negative age, empty string, out-of-range number
TypeError
Wrong type entirely: passing a string where a number is expected
RuntimeError
Logical impossibility: system in a state that should never occur

Writing Good Error Messages

✕ Bad
"Invalid input"
"Error"
"Something went wrong"
✓ Good
"age must be \(\ge\) 0, got -5"
"email must contain @"
"username exceeds 30 chars"
1
Name the parameter that failed validation.
2
State what was expected (the rule).
3
Show what was received (the actual value) when helpful.

Common Mistakes

✕ Raising a string
Writing raise "error" instead of raise ValueError("error"). Python 3 requires an exception object, not a string.
✕ Bare raise outside except
Using raise with no argument outside a try/except block. A bare raise only re-raises the current exception.
✕ Catching your own raise
Wrapping your guard clause inside a try/except that catches it immediately, silencing the error you just created.

Summary Reference

Concept Syntax / Rule Example
Basic raise raise ExcType("msg") raise ValueError("...")
Guard clause if invalid: raise if \(x < 0\): raise ...
Wrong value ValueError Negative age, empty name
Wrong type TypeError String instead of int
Good message Name + rule + actual "age must be \(\ge\) 0, got -3"
Placement Top of function Before main logic

Question 1 of 5

What is the correct way to raise a ValueError with a message in Python 3?

Question 2 of 5

What happens when you call calculate_speed(100, 0)?

Question 3 of 5

A function expects an integer but receives a string. Which exception type is most appropriate to raise?

Question 4 of 5

Where should guard clauses that raise exceptions be placed inside a function?

Question 5 of 5

What does withdraw(100, 150) produce?