Raising
Exceptions
Learn to intentionally raise exceptions in Python to guard against invalid states and write defensive, robust code.
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
Why Raise Exceptions?
The raise Statement
Anatomy of a raise Statement
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
Example 1: Validating Age
Example 2: Multiple Guards
Example 3: User Registration
The Guard Clause Pattern
Choosing the Right Exception Type
Writing Good Error Messages
"Error"
"Something went wrong"
"email must contain @"
"username exceeds 30 chars"
Common Mistakes
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
def calculate_speed(distance, time):
if time == 0:
raise ValueError("time cannot be zero")
return distance / time
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
def withdraw(balance, amount):
if amount <= 0:
raise ValueError("amount must be positive")
if amount > balance:
raise ValueError("insufficient funds")
return balance - amount
What does withdraw(100, 150) produce?