How to Raise an Exception in Python

Use the raise statement when you want your program to stop and show a clear error on purpose.

This is useful when your code detects invalid data, a missing value, or a rule that should not be broken. On this page, you will learn when to raise an exception, how to choose an exception type, and how to write a helpful error message.

Quick answer

age = -1

if age < 0:
    raise ValueError("age cannot be negative")

Use raise when your program detects invalid data or a rule that should not be broken.

What this page covers

  • Shows how to use the raise statement
  • Explains why you would raise an exception yourself
  • Focuses on simple built-in exceptions
  • Does not repeat full exception handling basics

What raise means

raise stops normal program flow and creates an exception at the exact place where your code finds a problem.

Use it when:

  • Input is invalid
  • A value breaks a rule
  • Your program reaches a state that should not happen

This helps you catch problems earlier and makes errors clearer.

For a beginner-friendly definition, see what an exception is in Python.

Basic raise syntax

The basic pattern is:

raise ValueError("message")

You write:

  • raise
  • an exception type
  • usually a short message string

Example:

name = ""

if name == "":
    raise ValueError("name cannot be empty")

In this example:

  • ValueError is the exception type
  • "name cannot be empty" is the error message

Choose an exception type that matches the problem.

When to raise an exception

Raise an exception when your code detects a problem that should stop normal execution.

Common cases:

  • An input value is not allowed
  • A required argument is missing or empty
  • A function gets the wrong type or wrong value
  • A business rule is broken, such as a negative price

Example:

price = -10

if price < 0:
    raise ValueError("price cannot be negative")

This is better than just printing a warning, because raise stops the program unless the exception is caught.

Common built-in exceptions to raise

Here are some common exception types beginners use.

ValueError

Use ValueError when the type is correct, but the value is not allowed.

age = -5

if age < 0:
    raise ValueError("age must be 0 or greater")

age is still an integer, so the type is fine. The problem is the value.

If you want more help with this error type, see ValueError in Python: causes and fixes.

TypeError

Use TypeError when the data type is wrong.

age = "twenty"

if not isinstance(age, int):
    raise TypeError("age must be an integer")

Here, age is a string instead of an integer.

KeyError

Use KeyError when a required dictionary key is missing.

user = {"name": "Ana"}

if "email" not in user:
    raise KeyError("email")

This is useful in custom checks when your code requires a key to exist.

RuntimeError

Use RuntimeError for a general program state problem when no better built-in exception fits.

is_connected = False

if not is_connected:
    raise RuntimeError("database connection is not available")

Try to use a more specific exception type if possible.

How to write a helpful error message

A good error message should be short and specific.

Try to include:

  • What was wrong
  • What was expected
  • The bad value only if it helps debugging

Good examples:

raise ValueError("score must be between 0 and 100")
raise TypeError("name must be a string")
raise ValueError("quantity cannot be negative")

Less helpful examples:

raise ValueError("error")
raise ValueError("invalid")

Messages like "error" do not explain the real problem.

Raising exceptions inside functions

A very common place to use raise is at the start of a function.

Validate inputs early before the function does more work.

def calculate_total(price, quantity):
    if not isinstance(price, (int, float)):
        raise TypeError("price must be a number")

    if not isinstance(quantity, int):
        raise TypeError("quantity must be an integer")

    if price < 0:
        raise ValueError("price cannot be negative")

    if quantity < 1:
        raise ValueError("quantity must be at least 1")

    return price * quantity


print(calculate_total(9.99, 3))

Expected output:

29.97

Why this helps:

  • Bad input is caught immediately
  • The function is easier to debug
  • The caller gets a clear error message

If you are also learning how to catch these errors, read how to handle exceptions in Python.

Re-raising an exception

Inside an except block, you can use raise by itself to raise the same exception again.

This is called re-raising.

try:
    number = int("hello")
except ValueError:
    print("Could not convert the text to an integer")
    raise

What happens here:

  • int("hello") causes a ValueError
  • The except block runs
  • The message is printed
  • raise sends the same exception upward again

Use this when you want to inspect or log the error first, but still keep the original problem visible.

To learn more about try and except, see how to use try-except blocks in Python.

Custom exceptions

You can create your own exception class for program-specific rules.

For beginners, built-in exceptions are usually enough. Start there first.

Simple example:

class InvalidAgeError(Exception):
    pass


age = -2

if age < 0:
    raise InvalidAgeError("age cannot be negative")

Custom exceptions are helpful when a built-in name is too vague.

But in many beginner programs, ValueError or TypeError is clearer and simpler.

For a broader explanation, see raising exceptions in Python.

How this differs from try-except

These two ideas are related, but they do different jobs:

  • raise creates an exception
  • try-except catches and handles an exception

Example:

def set_age(age):
    if age < 0:
        raise ValueError("age cannot be negative")
    return age


try:
    result = set_age(-1)
    print(result)
except ValueError as error:
    print(f"Invalid input: {error}")

Expected output:

Invalid input: age cannot be negative

In this example:

  • set_age() raises the exception
  • try-except catches it and prints a message

If you want to learn the full pattern, read using try-except-else-and-finally in Python.

Common mistakes

These are common problems beginners run into when using raise.

Using print() instead of raise

print() only shows text. It does not stop the program.

age = -1

if age < 0:
    print("age cannot be negative")

This prints a message, but the program keeps going.

If the problem should stop execution, use:

age = -1

if age < 0:
    raise ValueError("age cannot be negative")

Raising the wrong exception type

Pick an exception type that matches the real problem.

  • Wrong type → TypeError
  • Wrong value → ValueError

Example:

value = "100"

if not isinstance(value, int):
    raise TypeError("value must be an integer")

Writing vague messages

Avoid messages like:

raise ValueError("invalid")

Better:

raise ValueError("quantity must be at least 1")

Using raise without a real validation check

Only raise an exception when your code has actually found a problem.

Bad example:

raise ValueError("something went wrong")

Better example:

quantity = 0

if quantity < 1:
    raise ValueError("quantity must be at least 1")

Confusing raise ValueError(...) with return False

These do different things.

  • return False sends back a normal value
  • raise ValueError(...) creates an error and stops normal flow

Use raise when the input or state is invalid and the caller should know about the error.

Useful commands for debugging

When you are testing exception code, these commands can help:

python your_script.py
print(type(value))
print(value)
help(ValueError)
help(TypeError)

These can help you check:

  • what type a value really has
  • what the bad value is
  • what a built-in exception means

FAQ

What is the difference between raise and print?

print only shows text. raise creates an actual exception and stops the normal flow unless it is caught.

Should I use ValueError or TypeError?

Use TypeError when the data type is wrong. Use ValueError when the type is correct but the value is not allowed.

Can I raise an exception without a message?

Yes, but a clear message is usually better for debugging.

Example:

raise ValueError

Usually this is more helpful:

raise ValueError("age cannot be negative")

Can I use raise inside a function?

Yes. This is a common place to validate arguments and stop bad input early.

What does raise by itself do?

Inside an except block, it raises the current exception again.

See also