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
๐ŸŒ
Real Python
realpython.com โ€บ ref โ€บ builtin-exceptions โ€บ valueerror
ValueError | Pythonโ€™s Built-in Exceptions โ€“ Real Python
>>> def set_age(age): ... if age < 0: ... raise ValueError("Age can't be negative") ... print(f"Age is {age} years") >>> set_age(-5) Traceback (most recent call last): ... ValueError: Age can't be negative ...
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ tutorial โ€บ errors.html
8. Errors and Exceptions โ€” Python 3.14.7 documentation
Look at the following example, which asks the user for input until a valid integer has been entered, but allows the user to interrupt the program (using Control-C or whatever the operating system supports); note that a user-generated interruption is signalled by raising the KeyboardInterrupt exception. >>> while True: ... try: ... x = int(input("Please enter a number: ")) ... break ... except ValueError: ...
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ raise valueerror - including variables in the error message
r/learnpython on Reddit: Raise ValueError - including variables in the error message
October 20, 2023 -

Hello everyone,

I am fairly new to Python so this question might seem a little stupid. For an assignment, I have to define a function which puts an x value into three categories A, B, C based on the input entered (I called it parameter).

def generic_function(parameter):
if parameter > 1:
    raise ValueError("Parameter too high: PARAMETER. The maximum parameter is 1.")
elif parameter >= 0.6:
    x = 'A'
elif parameter >= 0.4:
    x = 'B'
elif parameter >= 0.0:
    x = 'C'
return x

The issue I have is raising the ValueError when the entered value is greater than 1. I would like that the self-made error message includes the parameter I entered as input into the function.For example, if I enter 2, it should raise a ValueError and display it in the message after the colons.

ValueError("Parameter too high: 2. The maximum parameter is 1.")

I'd be grateful for answers and I hope I explained the problem thouroughly.

๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ python-valueerror-exception-handling-examples
Python ValueError: Exception Handling Examples & Fixes | DigitalOcean
Learn how to handle Python ValueError exceptions with code examples, common causes, and best practices. Read the full guide to fix errors fast.
๐ŸŒ
Carmatec
carmatec.com โ€บ home โ€บ python raise valueerror: complete guide with examples
Python Raise ValueError: Complete Guide with Examples
December 30, 2025 - You can omit the message (raise ValueError), but including a clear, specific message is strongly recommended for maintainability and debugging. python def set_temperature(temp): if not isinstance(temp, (int, float)): raise TypeError("Temperature must be a number") if temp < -273.15: raise ValueError(f"Temperature below absolute zero is invalid: {temp}") set_temperature(-300) # Raises ValueError
๐ŸŒ
Accuweb
accuweb.cloud โ€บ home โ€บ explain python valueerror exception handling (with real examples & best practices)
Explain Python ValueError Exception Handling (With Real Examples & Best Practices)
January 15, 2024 - A) It is raised when a function receives a value of the correct type but an invalid or inappropriate value. ... A) Use a try/except ValueError: block around the risky code. ... A) When validating function inputs and the type is correct but the ...
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.

Find elsewhere
๐ŸŒ
w3resource
w3resource.com โ€บ python โ€บ python-raise-exceptions-with-examples.php
Python Raising Exceptions: Learn How and When to Raise Errors
April 18, 2026 - This example demonstrates how to raise an exception within a loop. The function 'process_numbers' iterates over a list of numbers and raises a 'ValueError' if it encounters a negative number, halting the process and providing immediate feedback.
๐ŸŒ
Centron
centron.de โ€บ startseite โ€บ python valueerror exception handling examples
Python ValueError Exception Handling Examples
February 6, 2025 - Please enter a positive number: abc Traceback (most recent call last): File "/Users/pankaj/Documents/PycharmProjects/hello-world/journaldev/errors/valueerror_examples.py", line 11, in <module> x = int(input('Please enter a positive number:\n')) ValueError: invalid literal for int() with base 10: 'abc' Our program can raise ValueError in int() and math.sqrt() functions.
๐ŸŒ
APXML
apxml.com โ€บ courses โ€บ python-for-beginners โ€บ chapter-9-handling-errors-exceptions โ€บ python-raising-exceptions
Raising Python Exceptions | `raise` Statement
Imagine a function that calculates ... must be positive.") return length * width # Example usage try: area1 = calculate_rectangle_area(10, 5) print(f"Area 1: {area1}") area2 = calculate_rectangle_area(-4, 5) # This will raise an exception print(f"Area 2: {area2}") except ValueError ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ how-to-fix-valueerror-exceptions-in-python
ValueError Exceptions In Python - GeeksforGeeks
July 1, 2026 - Therefore, math.factorial() raises a ValueError when a negative value is passed. 2. Incorrect Unpacking of Values: ValueError can occur when the number of variables does not match the number of values being unpacked. ... ERROR! Traceback (most recent call last): File "<main.py>", line 2, in <module> ValueError: not enough values to unpack (expected 4, got 3) Explanation: list contains only three elements, but four variables are used during unpacking. Since Python cannot assign four variables from three values, a ValueError is raised.
๐ŸŒ
Byu
acme.byu.edu โ€บ 00000179-d4cb-d26e-a37b-fffb57750000 โ€บ exceptions-fileio-pdf pdf
6 Exceptions and File Input/Ouput Lab Objective:
raise, followed by the name of the exception class. As soon as an exception is raised, the program ยท stops running unless the exception is handled properly. ... Exception: ints and floats are different! ... ValueError: 'x' should not exceed 5.
๐ŸŒ
Turing
turing.com โ€บ kb โ€บ valueerror-in-python-and-how-to-fix
What is ValueError in Python & How to fix it
A ValueError is raised, for instance, if a negative integer is supplied to a square root operation. ... The output shown after running the aforementioned script is as follows. The output indicates that the ValueError occurred at line 2, where ...
๐ŸŒ
Rollbar
rollbar.com โ€บ home โ€บ how to fix valueerror exceptions in python
How to Fix ValueError Exceptions in Python | Rollbar
June 24, 2024 - Since the function expects a positive integer, running the above code raises a ValueError: Traceback (most recent call last): File "test.py", line 3, in <module> math.sqrt(-100) ValueError: math domain error ยท Hereโ€™s an example of a Python ValueError raised when trying to remove a value from a list where it does not exist:
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ how-to-fix-valueerror-exceptions-in-python
How To Fix Valueerror Exceptions In Python - GeeksforGeeks
January 30, 2024 - The ValueError Exception is often raised in Python when an invalid value is assigned to a variable or passed to a function while calling it. It also often occurs during unpacking of sequence data types as well as with functions when a return statement is used. ... A ValueError typically occurs when we pass an invalid argument to a function in Python. As an example...
๐ŸŒ
Real Python
realpython.com โ€บ python-raise-exception
Python's raise: Effectively Raising Exceptions in Your Code โ€“ Real Python
October 20, 2025 - For example, your argument to raise could be a custom function that returns an exception: ... >>> def exception_factory(exception, message): ... return exception(message) ... >>> raise exception_factory(ValueError, "invalid value") Traceback ...
๐ŸŒ
Kite
kite.com โ€บ python โ€บ answers โ€บ how-to-raise-a-valueerror-in-python
Kite is saying farewell - Code Faster with Kite
November 20, 2022 - P.S. Most of our code has been open sourced on Github here. It includes our data-driven Python type inference engine, Python public-package analyzer, desktop software, editor integrations, Github crawler and analyzer, and much more.
๐ŸŒ
Initial Commit
initialcommit.com โ€บ blog โ€บ valueerror-python
Python ValueError Exception โ€“ How to Identify & Handle
January 9, 2023 - With try/except you can catch the ValueError, and then raise the ValueError again with a more meaningful message. In this article, you learned about ValueErrors, how they are different from other built-in exceptions, and various ways to handle them. You started by briefly looking at what Exceptions are in Python and then specifically the ValueError, and why it's different than other Exceptions.
๐ŸŒ
Dummies
dummies.com โ€บ article โ€บ technology โ€บ programming-web-design โ€บ python โ€บ how-to-raise-exceptions-in-python-148326
How to Raise Exceptions in Python | dummies
December 27, 2021 - Type the following code into the window โ€” pressing Enter after each line: try: Ex = ValueError() Ex.strerror = "Value must be within 1 and 10." raise Ex except ValueError as e: print("ValueError Exception!", e.strerror)
Author: