It has two purposes.

jackcogdill has given the first one:

It's used for raising your own errors.

if something:
   raise Exception('My error!')

The second is to reraise the current exception in an exception handler, so that it can be handled further up the call stack.

try:
  generate_exception()
except SomeException as e:
  if not can_handle(e):
    raise
  handle_exception(e)
Answer from Ignacio Vazquez-Abrams on Stack Overflow
🌐
W3Schools
w3schools.com › python › ref_keyword_raise.asp
Python raise Keyword
Bootcamp Python Certificate Python Training ... The raise keyword is used to raise an exception. You can define what kind of error to raise, and the text to print to the user. ... If you want to use W3Schools services as an educational ...
🌐
W3Schools
w3schools.com › python › gloss_python_raise.asp
Python Raise an Exception
Raise an error and stop the program if x is lower than 0: x = -1 if x < 0: raise Exception("Sorry, no numbers below zero") Try it Yourself » · The raise keyword is used to raise an exception.
🌐
W3Schools
w3schools.com › python › python_try_except.asp
Python Try Except
Raise an error and stop the program if x is lower than 0: x = -1 if x < 0: raise Exception("Sorry, no numbers below zero") Try it Yourself » · The raise keyword is used to raise an exception.
🌐
W3Schools
w3schools.in › python › exception-handling
Python Exceptions Handling - W3Schools
try/except: catch the error and recover from exceptions hoist by programmers or Python itself. try/finally: Whether exception occurs or not, it automatically performs the clean-up action. assert: triggers an exception conditionally in the code. raise: manually triggers an exception in the code.
🌐
W3Schools
w3schools.com › python › trypython.asp
W3Schools online PYTHON editor
Run ❯ Get your own Python server · ❯Run Code Ctrl+Alt+R Change Orientation Ctrl+Alt+O Change Theme Ctrl+Alt+D Go to Spaces Ctrl+Alt+P · Traceback (most recent call last): File "demo_ref_keyword_raise.py", line 4, in <module> raise Exception("Sorry, no numbers below zero") Exception: Sorry, no numbers below zero
🌐
W3Schools
w3schools.com › python › python_ref_exceptions.asp
Python Built-in Exceptions
The table below shows built-in exceptions that are usually raised in Python: ❮ Previous Next ❯ · ★ +1 · Sign in to track progress · REMOVE ADS · PLUS · SPACES · GET CERTIFIED · FOR TEACHERS · BOOTCAMPS · CONTACT US · × · If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com ·
🌐
w3resource
w3resource.com › python › python-raise-exceptions-with-examples.php
Python Raising Exceptions: Learn How and When to Raise Errors
August 26, 2024 - Master raising exceptions in Python with detailed examples, covering built-in and custom errors, loops, and functions for robust error handling.
Find elsewhere
🌐
OpenStax
openstax.org › books › introduction-python-programming › pages › 14-5-raising-exceptions
14.5 Raising exceptions - Introduction to Python Programming | OpenStax
March 13, 2024 - The following class represents a pizza for sale. The SIZES dictionary maps an abbreviation to a size's name and price. Line 11 checks if the size received by the constructor is in the dictionary. Line 12 raises a ValueError with specific error message.
🌐
GeeksforGeeks
geeksforgeeks.org › python-raise-keyword
Python Raise Keyword - GeeksforGeeks
October 30, 2023 - In this article, we will learn how the Python Raise keyword works with the help of examples and its advantages.
🌐
DiscoverWebTech
discoverwebtech.com › web-application-development › learn-python-programming-w3schools
Learn Python Programming with W3Schools: Web Development
May 12, 2025 - Start learning Python programming for free on W3Schools. Understand basics, OOP, and more with hands-on tutorials for beginners.
🌐
GeeksforGeeks
geeksforgeeks.org › python › user-defined-exceptions-python-examples
User-defined Exceptions in Python with Examples - GeeksforGeeks
February 12, 2026 - Follow these steps to create and ... or any of its subclasses. Raise the Exception: Use the raise statement to raise the user-defined exception when a specific condition occurs....
🌐
W3Schools
w3schools.com › python › python_iterators.asp
Python Iterators
class MyNumbers: def __iter__(self): self.a = 1 return self def __next__(self): if self.a <= 20: x = self.a self.a += 1 return x else: raise StopIteration myclass = MyNumbers() myiter = iter(myclass) for x in myiter: print(x) Try it Yourself » ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com · HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
🌐
Python documentation
docs.python.org › 3 › tutorial › errors.html
8. Errors and Exceptions — Python 3.14.3 documentation
The sole argument to raise indicates the exception to be raised. This must be either an exception instance or an exception class (a class that derives from BaseException, such as Exception or one of its subclasses).
🌐
W3Schools
w3schools.com › python › python_getstarted.asp
Python Getting Started
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training ... At W3Schools, you can try Python without installing anything.
🌐
Python Tutorial
pythontutorial.net › home › python oop › python raise from
Python raise from - Python Tutorial
March 28, 2025 - Summary: in this tutorial, you will learn how to use the Python raise from statement to raise an exception with extra information.
🌐
Real Python
realpython.com › ref › keywords › raise
raise | Python Keywords – Real Python
In this tutorial, you'll learn how to raise exceptions in Python, which will improve your ability to efficiently handle errors and exceptional situations in your code.
🌐
W3Schools
w3schools.com › python › gloss_python_iterator_stop.asp
Python Stop Iteration
class MyNumbers: def __iter__(self): self.a = 1 return self def __next__(self): if self.a <= 20: x = self.a self.a += 1 return x else: raise StopIteration myclass = MyNumbers() myiter = iter(myclass) for x in myiter: print(x) Try it Yourself » · Python Iterator Tutorial Iterators Iterator vs Iterable Loop Through an Iterator Create an Iterator ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com
Top answer
1 of 11
4324

How do I manually throw/raise an exception in Python?

Use the most specific Exception constructor that semantically fits your issue.

Be specific in your message, e.g.:

raise ValueError('A very specific bad thing happened.')

Don't raise generic exceptions

Avoid raising a generic Exception. To catch it, you'll have to catch all other more specific exceptions that subclass it.

Problem 1: Hiding bugs

raise Exception('I know Python!') # Don't! If you catch, likely to hide bugs.

For example:

def demo_bad_catch():
    try:
        raise ValueError('Represents a hidden bug, do not catch this')
        raise Exception('This is the exception you expect to handle')
    except Exception as error:
        print('Caught this error: ' + repr(error))

>>> demo_bad_catch()
Caught this error: ValueError('Represents a hidden bug, do not catch this',)

Problem 2: Won't catch

And more specific catches won't catch the general exception:

def demo_no_catch():
    try:
        raise Exception('general exceptions not caught by specific handling')
    except ValueError as e:
        print('we will not catch exception: Exception')
 

>>> demo_no_catch()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in demo_no_catch
Exception: general exceptions not caught by specific handling

Best Practices: raise statement

Instead, use the most specific Exception constructor that semantically fits your issue.

raise ValueError('A very specific bad thing happened')

which also handily allows an arbitrary number of arguments to be passed to the constructor:

raise ValueError('A very specific bad thing happened', 'foo', 'bar', 'baz') 

These arguments are accessed by the args attribute on the Exception object. For example:

try:
    some_code_that_may_raise_our_value_error()
except ValueError as err:
    print(err.args)

prints

('message', 'foo', 'bar', 'baz')    

In Python 2.5, an actual message attribute was added to BaseException in favor of encouraging users to subclass Exceptions and stop using args, but the introduction of message and the original deprecation of args has been retracted.

Best Practices: except clause

When inside an except clause, you might want to, for example, log that a specific type of error happened, and then re-raise. The best way to do this while preserving the stack trace is to use a bare raise statement. For example:

logger = logging.getLogger(__name__)

try:
    do_something_in_app_that_breaks_easily()
except AppError as error:
    logger.error(error)
    raise                 # just this!
    # raise AppError      # Don't do this, you'll lose the stack trace!

Don't modify your errors... but if you insist.

You can preserve the stacktrace (and error value) with sys.exc_info(), but this is way more error prone and has compatibility problems between Python 2 and 3, prefer to use a bare raise to re-raise.

To explain - the sys.exc_info() returns the type, value, and traceback.

type, value, traceback = sys.exc_info()

This is the syntax in Python 2 - note this is not compatible with Python 3:

raise AppError, error, sys.exc_info()[2] # avoid this.
# Equivalently, as error *is* the second object:
raise sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]

If you want to, you can modify what happens with your new raise - e.g. setting new args for the instance:

def error():
    raise ValueError('oops!')

def catch_error_modify_message():
    try:
        error()
    except ValueError:
        error_type, error_instance, traceback = sys.exc_info()
        error_instance.args = (error_instance.args[0] + ' <modification>',)
        raise error_type, error_instance, traceback

And we have preserved the whole traceback while modifying the args. Note that this is not a best practice and it is invalid syntax in Python 3 (making keeping compatibility much harder to work around).

>>> catch_error_modify_message()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in catch_error_modify_message
  File "<stdin>", line 2, in error
ValueError: oops! <modification>

In Python 3:

raise error.with_traceback(sys.exc_info()[2])

Again: avoid manually manipulating tracebacks. It's less efficient and more error prone. And if you're using threading and sys.exc_info you may even get the wrong traceback (especially if you're using exception handling for control flow - which I'd personally tend to avoid.)

Python 3, Exception chaining

In Python 3, you can chain Exceptions, which preserve tracebacks:

raise RuntimeError('specific message') from error

Be aware:

  • this does allow changing the error type raised, and
  • this is not compatible with Python 2.

Deprecated Methods:

These can easily hide and even get into production code. You want to raise an exception, and doing them will raise an exception, but not the one intended!

Valid in Python 2, but not in Python 3 is the following:

raise ValueError, 'message' # Don't do this, it's deprecated!

Only valid in much older versions of Python (2.4 and lower), you may still see people raising strings:

raise 'message' # really really wrong. don't do this.

In all modern versions, this will actually raise a TypeError, because you're not raising a BaseException type. If you're not checking for the right exception and don't have a reviewer that's aware of the issue, it could get into production.

Example Usage

I raise Exceptions to warn consumers of my API if they're using it incorrectly:

def api_func(foo):
    '''foo should be either 'baz' or 'bar'. returns something very useful.'''
    if foo not in _ALLOWED_ARGS:
        raise ValueError('{foo} wrong, use "baz" or "bar"'.format(foo=repr(foo)))

Create your own error types when apropos

"I want to make an error on purpose, so that it would go into the except"

You can create your own error types, if you want to indicate something specific is wrong with your application, just subclass the appropriate point in the exception hierarchy:

class MyAppLookupError(LookupError):
    '''raise this when there's a lookup error for my app'''

and usage:

if important_key not in resource_dict and not ok_to_be_missing:
    raise MyAppLookupError('resource is missing, and that is not ok.')
2 of 11
579

Don't do this. Raising a bare Exception is absolutely not the right thing to do; see Aaron Hall's excellent answer instead.

It can't get much more Pythonic than this:

raise Exception("I know Python!")

Replace Exception with the specific type of exception you want to throw.

See the raise statement documentation for Python if you'd like more information.