Question
How can I manually raise an exception in Python so that it can later be caught by an except block?
Short Answer
By the end of this page, you will understand how to manually raise exceptions in Python using raise, how except catches them, when to use built-in exception types versus custom ones, and the common patterns developers use in real code.
Concept
In Python, exceptions are signals that something went wrong or that execution should stop unless the problem is handled. You raise an exception with the raise keyword.
This matters because programs often need to detect invalid input, impossible states, missing data, or failed operations. Instead of silently continuing with bad data, Python code can raise an exception and let another part of the program handle it with try/except.
Basic idea:
raise ValueError("Invalid age")
When Python sees this, it stops normal execution at that line and looks for a matching except block.
A full example:
try:
raise ValueError("Invalid age")
except ValueError as e:
print("Caught:", e)
Exceptions are useful because they:
- make errors explicit
- separate normal logic from error-handling logic
- help you fail early when input or state is wrong
- let callers decide how to recover
Python includes many built-in exception types such as:
ValueErrorfor correct type but bad valueTypeErrorfor wrong typeKeyErrorfor missing dictionary keyIndexErrorfor invalid list indexRuntimeErrorfor general runtime problems
You can also define your own custom exceptions when built-in ones are not descriptive enough.
Mental Model
Think of an exception like pulling a fire alarm in a building.
- Normal code execution is people working normally.
raiseis pulling the alarm.- Python immediately stops the current normal flow.
exceptis the emergency response plan that catches the alarm and decides what to do next.
If no one responds to the alarm, the program stops and shows an error.
So raise does not just create a message. It changes the control flow of your program.
Syntax and Examples
The core syntax is:
raise ExceptionType("message")
Basic example
age = -5
if age < 0:
raise ValueError("Age cannot be negative")
Here, ValueError is raised because the value is invalid.
Catching the raised exception
try:
age = -5
if age < 0:
raise ValueError("Age cannot be negative")
except ValueError as error:
print("Caught error:", error)
Output:
Caught error: Age cannot be negative
Raising a generic exception
raise Exception("Something went wrong")
This works, but in real code it is usually better to use a more specific exception type.
Step by Step Execution
Consider this example:
def divide(a, b):
if b == 0:
raise ZeroDivisionError("Cannot divide by zero")
return a / b
try:
result = divide(10, 0)
print(result)
except ZeroDivisionError as error:
print("Caught:", error)
Step by step:
-
Python defines the
dividefunction. -
Execution enters the
tryblock. -
divide(10, 0)is called. -
Inside
divide, Python checksif b == 0. -
Since
bis0, Python executes:raise ZeroDivisionError()
Real World Use Cases
Manual exceptions appear in many practical situations.
Input validation
def set_age(age):
if age < 0:
raise ValueError("Age must be 0 or greater")
Used in forms, APIs, and command-line tools.
Business rules
def withdraw(balance, amount):
if amount > balance:
raise ValueError("Insufficient funds")
return balance - amount
Used in banking, checkout flows, and inventory systems.
Configuration checks
def load_config(config):
if "database_url" not in config:
raise KeyError("Missing 'database_url' setting")
Used when applications start and require mandatory settings.
API and data processing safeguards
Real Codebase Usage
In real projects, developers use raise as part of clear error-handling design.
Guard clauses
A guard clause checks invalid conditions early and stops immediately.
def calculate_discount(price):
if price < 0:
raise ValueError("price cannot be negative")
return price * 0.9
This keeps the rest of the function simpler.
Validation at boundaries
Developers often raise exceptions when data enters the system.
def create_user(email):
if "@" not in email:
raise ValueError("Invalid email address")
This prevents bad data from spreading deeper into the codebase.
Converting low-level errors into domain-specific errors
class ConfigError(Exception):
pass
def ():
:
(config[])
KeyError:
ConfigError()
ValueError:
ConfigError()
Common Mistakes
1. Raising a string instead of an exception
This is invalid in modern Python.
Broken code:
raise "Something went wrong"
Correct:
raise Exception("Something went wrong")
2. Using overly generic Exception everywhere
This works, but it makes errors harder to handle precisely.
Less helpful:
raise Exception("Bad input")
Better:
raise ValueError("Age must be positive")
3. Catching the wrong exception type
try:
raise ValueError("Bad value")
except TypeError:
print("This will not run")
Make sure the except type matches the raised exception or a parent class.
Comparisons
| Concept | Purpose | Example | When to use |
|---|---|---|---|
raise | Manually trigger an exception | raise ValueError("Bad input") | When your code detects an error condition |
try/except | Handle an exception | except ValueError: | When you want to recover or report the error |
return | Send back a normal result | return 42 | When execution succeeds normally |
print | Display information |
Cheat Sheet
Core syntax
raise ValueError("Invalid value")
Catching it
try:
raise ValueError("Invalid value")
except ValueError as error:
print(error)
Custom exception
class MyError(Exception):
pass
raise MyError("Something specific went wrong")
Re-raise current exception
try:
do_work()
except Exception:
raise
Quick rules
- Use
raiseto trigger an exception manually. - Raise exception objects or exception classes derived from
Exception. - Prefer specific exceptions like
ValueErrorover genericException.
FAQ
How do you manually throw an exception in Python?
Use the raise keyword:
raise ValueError("Something is wrong")
Can I catch a manually raised exception with except?
Yes. If the except block matches the exception type, it will catch it.
What exception type should I raise in Python?
Use the most specific built-in exception that matches the problem, such as ValueError or TypeError. Create a custom exception when needed.
Can I raise my own custom exception in Python?
Yes. Define a class that inherits from Exception, then raise it.
What happens after raise is executed?
Normal execution stops immediately, and Python looks for a matching except block.
Is raise Exception(...) okay to use?
Yes, but it is usually better to raise a more specific exception so the error is clearer and easier to handle.
What is the difference between raise and ?
Mini Project
Description
Build a small input-validation function for a registration system. The function should check whether a username and age are valid. If the data is invalid, it should raise meaningful exceptions. This demonstrates how to use raise to protect your program from bad input and how to catch those errors cleanly.
Goal
Create a Python function that validates registration data and raises exceptions for invalid values, then handle those exceptions with try/except.
Requirements
- Create a function that accepts a username and an age.
- Raise a
ValueErrorif the username is empty. - Raise a
ValueErrorif the age is negative. - Return a success message when the input is valid.
- Use a
try/exceptblock to catch and print validation errors.
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Catch Multiple Exceptions in One except Block in Python
Learn how to catch multiple exceptions in one Python except block using tuples, with examples, mistakes, and real-world usage.
Convert Bytes to String in Python 3
Learn how to convert bytes to str in Python 3 using decode(), text mode, and proper encodings with practical examples.