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.')
Answer from Aaron Hall on Stack Overflow
🌐
Python documentation
docs.python.org › 3 › tutorial › errors.html
8. Errors and Exceptions — Python 3.14.7 documentation
# exc must be exception instance or None. raise RuntimeError from exc · This can be useful when you are transforming exceptions. For example: >>> def func(): ... raise ConnectionError ... >>> try: ... func() ... except ConnectionError as exc: ... raise RuntimeError('Failed to open database') from exc ...
Top answer
1 of 11
4330

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.

Discussions

Explain the term “raise an exception” without using the terms “raise” or “throw”
Try reading about excepting handling in python with some example code, this should help you understand. https://www.programiz.com/python-programming/exception-handling TL;DR; sequential execution is stopped when an exception happens, and it looks for an except: block to handle it, and starts executing a matching except block. If no such block found anywhere, including above functions etc, it is finally shown as an error to the user stopping the entire code. More on reddit.com
🌐 r/learnpython
11
0
February 23, 2022
To raise exceptions, or to return None. Best practices?
Is the fetch failing exceptional? Like, if the fetch fails, are you going to think "oh yeah, sometimes that just doesn't exist" or "weird, why did that fail?" The former should probably just return None, and the later should probably raise an exception as a rough rule of thumb. More on reddit.com
🌐 r/learnpython
42
14
October 2, 2024
Meaning of RuntimeError
The quip in the docs is that it’s “any other error”, while some specific RuntimeErrors are pretty low level, like recursion limit exceeded or stop iteration conversion. THe reason for asking is the use of if xx: raise RuntimeError("cannot blah blah") in some library/pr that I’m reviewing. More on discuss.python.org
🌐 discuss.python.org
4
0
June 20, 2024
Runtime warnings in Python
Hi, I’m new to Python and I have some questions about how to handle runtime warnings/errors. I have two examples originating in the same function. RuntimeWarning: overflow encountered in power return d+(a-d)/(1+(x/c)**b)**g RuntimeWarning: invalid value encountered in power return ... More on discuss.python.org
🌐 discuss.python.org
13
0
April 29, 2024
🌐
W3Schools
w3schools.com › python › gloss_python_raise.asp
Python Raise an Exception
As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword. Raise an error and stop the program if x is lower than 0:
🌐
Real Python
realpython.com › ref › builtin-exceptions › runtimeerror
RuntimeError | Python’s Built-in Exceptions – Real Python
Debugging complex code where the exact nature of the error isn’t immediately clear · You should use RuntimeError sparingly. ... >>> numbers = {1, 2, 3} >>> for item in numbers: ... numbers.remove(item) ... Traceback (most recent call last): ... RuntimeError: Set changed size during iteration
🌐
Python
docs.python.org › 3 › builtins › exceptions.html
Built-in Exceptions — Python 3.14.7 documentation
If a generator code directly or indirectly raises StopIteration, it is converted into a RuntimeError (retaining the StopIteration as the new exception’s cause). Changed in version 3.3: Added value attribute and the ability for generator functions ...
🌐
Reddit
reddit.com › r/learnpython › explain the term “raise an exception” without using the terms “raise” or “throw”
r/learnpython on Reddit: Explain the term “raise an exception” without using the terms “raise” or “throw”
February 23, 2022 -

I’m a python learner and am pretty ok with the syntax, and am now finding myself struggling with some of the deeper concepts, in this case error handling. Our environment is python running in a pytest framework using some pre-structured functions along with scripts and functions we write ourselves. I have visibility into the scripts and functions I write, along with some of the pre-structured functions, but the lowest level functions are beyond my view and control. I regularly run into exceptions in these lower levels and am trying to understand what’s going on. All the references I find say something like “raising an exception is when an executions error occurs, the error is raised as an exception”. This makes me nuts as they are explaining the term by using the term. So… Q1: what happens when an “exception is raised”? In terms of program execution and control and variables. Q2: if my script calls a function1 that calls a function2 which contains a command that “raises an exception” can I catch and handle it in function1 or in my top-level script, and if so, how? Q3: if I’m asking the wrong question, what should I be asking and/or researching?

Top answer
1 of 5
4
Try reading about excepting handling in python with some example code, this should help you understand. https://www.programiz.com/python-programming/exception-handling TL;DR; sequential execution is stopped when an exception happens, and it looks for an except: block to handle it, and starts executing a matching except block. If no such block found anywhere, including above functions etc, it is finally shown as an error to the user stopping the entire code.
2 of 5
4
So… Q1: what happens when an “exception is raised”? Go back a step - what happens when a function is called? Maybe you've got an idea, but let's be explicit - what happens is that the interpreter "puts a pin" in what it's currently doing, the line it's currently executing, and it jumps to the body of the function and executes that. Only it's not actually a pin, it's a stack frame. It puts a frame on the call stack - a collection of these frames, in the form of a stack, that the interpreter is using to keep track of where it needs to go back to when the function returns - and starts executing the body of the function that was called. If that function calls a function, then another frame goes on the call stack and you jump into the body of the new function. When the function returns, you "pop" a frame off the stack, and you return to where the function was called, possibly holding a return value. If you've written functions that call functions (that call functions, etc...) then you've had some intuitive notion of "returning" all the way back to where you started. That's called "unwinding the stack." When you raise an exception, somewhere deep in a nest of called functions, what the interpreter does is start removing stack frames from the stack, immediately returning functions wherever they're currently at in their execution. It keeps track as it does so, and you see that in the error output as something called the exception stacktrace: Traceback (most recent call last): File "/path/to/example.py", line 4, in greet('Chad') File "/path/to/example.py", line 2, in greet print('Hello, ' + someon) NameError: name 'someon' is not defined The interpreter pops stack frames until one of two things happens - either you pop all the way to an empty stack and your Python program exits with a relevant error code, or you pop into the body of a try block. If the try block is followed by an except block that declares it can handle errors of that type (so, except NameError to catch our example exception above) then the interpreter stops popping stack frames and moves execution to that except block and continues from there. That's what it means to raise an exception - it means "start to unwind the execution call stack of your program until the interpreter finds itself in a frame where the exception can be handled, or it runs out of frames."
Find elsewhere
🌐
OneUptime
oneuptime.com › home › blog › how to handle exceptions properly in python
How to Handle Exceptions Properly in Python
January 24, 2026 - # Assertions are for catching programming errors (bugs) def calculate_average(numbers): assert len(numbers) > 0, "Cannot calculate average of empty list" return sum(numbers) / len(numbers) # Exceptions are for runtime errors (expected failures) def load_config(filepath): if not os.path.exists(filepath): raise FileNotFoundError(f"Config not found: {filepath}") with open(filepath) as f: return json.load(f) # Assertions can be disabled with python -O # Never use assertions for input validation!
🌐
Reddit
reddit.com › r/learnpython › to raise exceptions, or to return none. best practices?
r/learnpython on Reddit: To raise exceptions, or to return None. Best practices?
October 2, 2024 -

Hi there,

I’ve recently been trying to write type safe code by enforcing strict mypy checking.

In doing so, I’ve realised some holes in my general code style and want to make it A) consistent throughout the code base and B) do it the most pythonic way.

I’m using this with c extension APIs so I’m just going to make up some very contrived examples

Let’s say we have a function which fetches an instance of an object

def get_item(name: str) -> ItemClass:
    if item := api.get_item({‘name’: name}):
        return item

I have to try retrieve the object- at this point I may have the object or I may have “None” or “False” depending on the call.

Using mypy, it requires a return call at the end of the function (a good thing imo). So naturally I add “return None”

But now of course I have to change my function signature.

def get_item(name: str) -> Optional[ItemClass]:
    if item := api.get_item({‘name’: name}):
        return item
    return None

This works, and it still boils down to me having to check the truthyness of the returned value from my function, but I’m wondering if the more pythonic thing to do would be to raise an exception instead of returning None.

What is the communities feeling of best practice? And especially how it ties into writing code that is robust

Many thanks for your time

🌐
APXML
apxml.com › courses › python-for-beginners › chapter-9-handling-errors-exceptions › python-raising-exceptions
Raising Python Exceptions | `raise` Statement
raise ExceptionType("Optional descriptive message about the error") Here, ExceptionType is the class of the exception you want to raise. Python has many built-in exception types suitable for various error conditions. It's generally good practice to use the most specific, appropriate built-in exception type available.
🌐
Honeybadger
honeybadger.io › blog › a-guide-to-exception-handling-in-python
The ultimate guide to Python exception handling - Honeybadger Developer Blog
March 28, 2025 - Discover powerful Python exception-handling techniques with this guide. Learn about nested try blocks, re-raising exceptions, custom exceptions, and more.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-exception-handling
Python Exception Handling - GeeksforGeeks
Helps improve program reliability ... an exception and handle it gracefully: ... Can't be divided by zero! Explanation: Dividing a number by 0 raises ......
Published: May 29, 2026
🌐
Coursera
coursera.org › tutorials › how to catch, raise, and print a python exception
How to Catch, Raise, and Print a Python Exception | Coursera
August 13, 2024 - In the code block above, TypeError is the specified error. It has been set to occur anytime the variable x is not a string. The text inside the parentheses represents your chosen text to print to the user. How would you raise an exception that prints "Sorry, please enter a number greater than or equal to 0" if x is a negative number? ... In an exception block, define the exception and use the print() function. Here’s an example: ... Why isn’t Python printing my exception?
🌐
Rollbar
rollbar.com › home › throwing exceptions in python
How to Throw Exceptions in Python | Rollbar
Sometimes you want Python to throw a custom exception for error handling. You can do this by checking a condition and raising the exception, if the condition is True.
Published: May 22, 2026
🌐
Real Python
realpython.com › python-exceptions
Python Exceptions: An Introduction – Real Python
March 18, 2026 - As you saw earlier, when syntactically correct code runs into an error, Python will raise an exception error. This exception error will crash the program if you don’t handle it. In the except clause, you can determine how your program should respond to exceptions. The following function can help you understand the try and except block: ... def linux_interaction(): import sys if "linux" not in sys.platform: raise RuntimeError("Function can only run on Linux systems.") print("Doing Linux things.")
🌐
Python.org
discuss.python.org › python help
Meaning of RuntimeError - Python Help - Discussions on Python.org
June 20, 2024 - The quip in the docs is that it’s “any other error”, while some specific RuntimeErrors are pretty low level, like recursion limit exceeded or stop iteration conversion. THe reason for asking is the use of if xx: raise RuntimeError("cannot blah blah") in some library/pr that I’m reviewing.
🌐
Python.org
discuss.python.org › python help
Runtime warnings in Python - Python Help - Discussions on Python.org
April 29, 2024 - Hi, I’m new to Python and I have some questions about how to handle runtime warnings/errors. I have two examples originating in the same function. RuntimeWarning: overflow encountered in power return d+(a-d)/(1+(x/c)**b)**g RuntimeWarning: invalid value encountered in power return d+(a-d)/(1+(x/c)**b)**g Its not really a problem as the program executes as intended.
🌐
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.
🌐
Quora
quora.com › Does-raising-an-exception-stop-execution-in-Python
Does raising an exception stop execution in Python? - Quora
Answer (1 of 5): It might, but everything depends on how you write your Python code. The joy have having try / except syntax is precisely that it gives you an opportunity to handle the exception and prevent a crash, where a 1970s era language, such as FORTRAN, might have been forced to stand down.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-raise-keyword
Python Raise Keyword - GeeksforGeeks
May 12, 2026 - The error can be a 'ValueError' or a 'ZeroDivisionError' or some other type of error. Below is the syntax: ... Example: In the below code, we try to convert a string into an integer. If conversion fails, we raise a ValueError.
🌐
Real Python
realpython.com › python-raise-exception
Python's raise: Effectively Raising Exceptions in Your Code – Real Python
October 20, 2025 - You can raise custom exceptions by defining new exception classes derived from Exception. The difference between raise and assert lies in their use. You use assert for debugging, while raise is used to signal runtime errors.