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
docs.python.org › 3 › builtins › exceptions.html
Built-in Exceptions — Python 3.14.7 documentation
Passing arguments of the wrong type (e.g. passing a list when an int is expected) should result in a TypeError, but passing arguments with the wrong value (e.g. a number outside expected boundaries) should result in a ValueError. ... Raised when a reference is made to a local variable in a function or method, but no value has been bound to that variable. This is a subclass of NameError. ... Raised when a Unicode-related encoding or decoding error occurs.
🌐
Python documentation
docs.python.org › 3 › tutorial › errors.html
8. Errors and Exceptions — Python 3.14.7 documentation
For this purpose, exceptions have ... all notes, in the order they were added, after the exception. >>> try: ... raise TypeError('bad type') ......
Discussions

Manually raising (throwing) an exception in Python - Stack Overflow
In this case, we specified False ... to raise to, we add a comma and specify the error text we want. In this case, I wrote Manually raised error and this raises it with that text. ... asserts will be disabled when the interpreter is run with optimizations, so should not be used for control flow. see comments on Rehan Haider's answer 2023-11-06T02:27:50.647Z+00:00 ... You should learn the raise statement of Python for that. It should be kept inside the try block. ... try: raise TypeError # Replace ... More on stackoverflow.com
🌐 stackoverflow.com
Proper way in Python to raise errors while setting variables - Stack Overflow
The standard way of signalling an error in python is to raise an exception and let the calling code handle it. Either let the NameError & TypeError carry on upwards, or catch them and raise an InvalidPassword exception that you define. More on stackoverflow.com
🌐 stackoverflow.com
python - Possible to raise two types of errors? - Stack Overflow
So I'm experimenting making my own program. I have the user input a string and an integer (name, age). I want to raise a Value Error if the age is under 1 (if age > 1:) I did that. But I'm not sur... More on stackoverflow.com
🌐 stackoverflow.com
How to type correctly the return of functions that raise exception?
By the way, you generally shouldn't catch an exception and raise a different one. If it's important to change the type, you should at least do: try: ... except KeyError as error: raise FooKeyNotFoundException from error https://docs.python.org/3/tutorial/errors.html#exception-chaining More on reddit.com
🌐 r/Python
9
2
August 12, 2021
🌐
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:
🌐
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.
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.

Top answer
1 of 3
70

Your code is out of a context so is not obvious the right choice. Following some tips:

  • Don't use NameError exception, it is only used when a name, as the exception itself said, is not found in the local or global scope, use ValueError or TypeError if the exception concerns the value or the type of the parameter;

  • Don't print error messages. Raise meaningful exceptions with a meaningful error message:

    raise ValueError("password must be longer than 6 characters")
    
  • Returning a value from a setter is meaningless while assignment is not an expression, i.e. you cannot check the value of an assignment:

    if (user.password = 'short'): ...
    
  • Just raise an exception in the setter and let the code that set the property handle it.

Example:

class Test:

    minlen = 6

    @property
    def password(self):
        return self._password

    @password.setter
    def password(self, value):
        if not isinstance(value, basestring):
            raise TypeError("password must be a string")
        if len(value) < self.minlen:
            raise ValueError("password must be at least %d character len" % \
                                 self.minlen)
        self._password = value

Look also at this forms handling library, there the validators , here an example, are entities in their own: they can be set dynamically with higher control and less coupled code, but maybe this is much more than you need.

2 of 3
10

The standard way of signalling an error in python is to raise an exception and let the calling code handle it. Either let the NameError & TypeError carry on upwards, or catch them and raise an InvalidPassword exception that you define.

While it is possible to return a success/fail flag or error code from the function as you have done, it is not recommended - it is easy for the caller to forget to check the return value and have errors get lost. Besides you are returning a value from a property setter - this is meaningless in Python since assignments are not expressions and cannot return a value.

You should also never print a message for the user in your exception handling - what if you later want to use the function or class in a GUI program? In that case your print statement will have nowhere to print to. Logging an error to a logfile (using Python's logging module) is often helpful for debugging though.

🌐
Qodo
qodo.ai › blog › learn › common python error types and how to resolve them
Common Python error types and how to resolve them
March 20, 2025 - For instance, the hasattr() function verifies attribute existence before access, while getattr() provides a safe way to access attributes with fallback values. For class-based implementations, we can define all attributes explicitly in the __init__ method, and do consider using dataclasses for more structured management of attributes. When a variable or function hasn’t been defined in the current scope, Python raises a NameError. While seemingly straightforward, like some of the other errors above, these errors too can become deceptively complex in larger codebases, especially when dealing with nested scopes and module imports.
Find elsewhere
🌐
Tutorial Teacher
tutorialsteacher.com › python › error-types-in-python
Error Types in Python
Learn about built-in error types in Python such as IndexError, NameError, KeyError, ImportError, etc.
🌐
Medium
medium.com › @mathur.danduprolu › handling-errors-in-python-try-except-custom-exceptions-and-more-26a6aa436d20
Handling Errors in Python: Try-Except, Custom Exceptions, and More | by Mathur Danduprolu | Medium
October 30, 2024 - ValueError: Raised when a function gets an argument of the correct type but an inappropriate value. IndexError: Happens when trying to access an index that is out of range. KeyError: Raised when accessing a dictionary key that doesn’t exist.
🌐
Rollbar
rollbar.com › home › throwing exceptions in python
How to Throw Exceptions in Python | Rollbar
Before diving in, it's important to understand the two types of unwanted conditions in Python programming—syntax error and exception. The syntax error exception occurs when the code does not conform to Python keywords, naming style, or programming ...
Published: May 22, 2026
🌐
Programiz
programiz.com › python-programming › exceptions
Python Exceptions (With Examples)
Whenever these types of runtime errors occur, Python creates an exception object. If not handled properly, it prints a traceback to that error along with some details about why that error occurred. ... Traceback (most recent call last): File "<string>", line 1, in <module> ZeroDivisionError: division by zero · Here, while trying to divide 7 / 0, the program throws a system exception ZeroDivisionError · Illegal operations can raise exceptions.
🌐
DataCamp
datacamp.com › tutorial › exception-handling-python
Exception & Error Handling in Python | Tutorial by DataCamp | DataCamp
May 29, 2026 - RuntimeError: occurs when an error does not fall into any category. NameError: raised when a variable is not found in the local or global scope. MemoryError: raised when programs run out of memory. ValueError: occurs when the operation or function receives an argument with the right type but the wrong value. ZeroDivisionError: raised when you divide a value or variable with zero. SyntaxError: raised by the parser when the Python syntax is wrong.
🌐
Rollbar
rollbar.com › home › what are the different types of python errors? – and how to handle them
What are the Different Types of Python Errors? – and How to Handle Them
Learn how to fix common Python errors: SyntaxError, TypeError, NameError, IndexError, and more. Each error type explained with code examples and solutions.
Published: July 14, 2025
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-raise-keyword
Python Raise Keyword - GeeksforGeeks
May 12, 2026 - Traceback (most recent call last): ... <module> raise Exception("The number shouldn't be an odd integer") Exception: The number shouldn't be an odd integer · We can check the type of error which have occurred during the execution of our code. 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 ...
🌐
Last9
last9.io › blog › types-of-errors-in-python
Types of Errors in Python: Syntax, Runtime, and Logical Explained | Last9
January 3, 2025 - If you try to access an attribute that doesn’t exist, Python raises an AttributeError. Typo in the attribute name: Misspelling a method or variable name can result in an AttributeError. Accessing attributes from non-initialized or None objects: Trying to access attributes from None or an uninitialized object will raise this error. Trying to access attributes of the wrong type of object: If you’re working with a variable that isn’t the object type you expect, trying to call a method or access an attribute that isn’t defined on it will trigger an AttributeError.
🌐
Medium
medium.com › @andrewdass › python-errors-exceptions-and-the-raise-keyword-f5226ccbcf19
Python: Errors, Exceptions and the Raise Keyword | by Andrew Dass | Medium
April 1, 2025 - ... A syntax error occurs when a statement is entered in Python, but it is written incorrectly, or something is missing. Below is the script that was used to receive the many errors shown above.
🌐
Real Python
realpython.com › ref › builtin-exceptions
Python’s Built-in Exceptions (Reference) – Real Python
IOError Is used to handle input/output (I/O) related errors, such as problems reading or writing files. IsADirectoryError Occurs when an operation expected to be performed on a file is attempted on a directory instead. KeyboardInterrupt Occurs when the user interrupts the execution of a program using the keyboard. KeyError Occurs when you try to access a missing key in a dictionary. LookupError Serves as the base class for exceptions raised when a key or index used on a mapping or sequence is invalid.
🌐
Execute Program
executeprogram.com › courses › python-for-programmers › lessons › raising-exceptions
Python for Programmers: Raising Exceptions
Learn programming languages like TypeScript, Python, JavaScript, SQL, and regular expressions. Interactive with real code examples.