🌐
Python documentation
docs.python.org › 3 › tutorial › errors.html
8. Errors and Exceptions — Python 3.14.7 documentation
As you can see, the finally clause is executed in any event. The TypeError raised by dividing two strings is not handled by the except clause and therefore re-raised after the finally clause has been executed.
🌐
Real Python
realpython.com › ref › builtin-exceptions › typeerror
TypeError | Python’s Built-in Exceptions – Real Python
>>> def run_callback(callback, *args, **kwargs): ... if not callable(callback): ... raise TypeError("callback must be callable") ... return callback(*args, **kwargs) ... >>> run_callback(42) Traceback (most recent call last): ... TypeError: callback must be callable ... In this tutorial, you'll get to know some of the most commonly used built-in exceptions in Python.
Discussions

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 - raise TypeError exception for incorrect input value in a class - Stack Overflow
I am trying to write a class and I want that if the initial input values for the class don't obey specific types, it would raise an exception. For instance I would use except TypeError to return an... More on stackoverflow.com
🌐 stackoverflow.com
Manually raising (throwing) an exception in Python - Stack Overflow
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 ... More on stackoverflow.com
🌐 stackoverflow.com
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
🌐
GeeksforGeeks
geeksforgeeks.org › python › handling-typeerror-exception-in-python
Handling TypeError Exception in Python - GeeksforGeeks
August 22, 2025 - Trying to use a variable like a string or number as if it were a function will raise a TypeError. ... To fix this error, just print the variable without parentheses. ... Python list indices must be integers or slices.
🌐
Python
docs.python.org › 3 › builtins › exceptions.html
Built-in Exceptions — Python 3.14.7 documentation
Raised when a Unicode-related error occurs during translating. It is a subclass of UnicodeError. ... Raised when an operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described ...
🌐
B-List
b-list.org › weblog › 2023 › dec › 11 › python-exceptions
Raise the right exceptions - James Bennett
December 11, 2023 - Which then raises the question of which exception(s) to raise, and that’s the real tip I want to get across today. The short answer is: TypeError for the case of a non-numeric argument, ValueError for the case of divisor=0. The longer answer is that when you want to do some sort of validation of arguments passed to a Python function or method, TypeError is how you indicate a violation of your function or method’s signature: either you received too many arguments, or too few, or one or more arguments you received were of the wrong type.
🌐
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:
🌐
PythonForBeginners.com
pythonforbeginners.com › home › typeerror in python
TypeError in Python - PythonForBeginners.com
December 28, 2022 - On the other hand, if we call a ... it will raise a TypeError exception with the message “TypeError: ‘int’ object is not callable” as follows. ... Traceback (most recent call last): File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 2, in <module> myInt() TypeError: 'int' object is not callable · Errors are inevitable ...
🌐
Pronod's Blog
data-intelligence.hashnode.dev › handling-typeerror-in-python-guide
Understanding and Fixing Python TypeErrors - Pronod's Blog
September 13, 2024 - Wrap the code that might raise a TypeError inside a try block and catch the exception in the except block. # Example: Handling TypeError with try-except try: result = "Hello" + 123 except TypeError as e: print("Error:", e)
Find elsewhere
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.

🌐
Openastronomy
openastronomy.org › rcsc18 › chapters › 05-writing-effective-tests › 02-explicit-exceptions
Raising Errors - Research Computing Summer School
TypeError should be raised when the type (i.e. str, float, int) is incorrect. Not all programming errors raise an exception, some are errors in the functioning of the code. i.e. this: ... This is obviously incorrect, but Python does not know any difference, it executes the code as written and ...
🌐
Rollbar
rollbar.com › home › how to fix typeerror exceptions in python
How to Fix TypeError Exceptions in Python | Rollbar
Since addition cannot be performed ... operand type(s) for +: 'int' and 'str' To avoid type errors in Python, the type of an object should be checked before ......
Published: October 1, 2022
🌐
Hyperskill
hyperskill.org › university › python › python-raise-exception
Python Raise Exception
August 2, 2024 - When working with Python exceptions are triggered to signal when an error or unexpected situation arises while a program is running. The raise keyword is employed to specifically trigger these exceptions. This feature enables developers to generate and handle both customized exceptions.
🌐
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 ...
🌐
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.
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.

🌐
Luke Plant
lukeplant.me.uk › blog › posts › raising-exceptions-or-returning-error-objects-in-python
Raising exceptions or returning error objects in Python - lukeplant.me.uk
June 6, 2022 - In the years since I wrote the code, however, some perhaps more compelling arguments have come along for the error object method. First, with some small changes (specifically, removing the sentinel singleton value), we can now add a type signature for email_from_token: def email_from_token(self, token, max_age=None) -> str | VerifyFailed | VerifyExpired: ... (You may need typing.Union for older Python versions)
🌐
Better Stack
betterstack.com › community › questions › how-to-raise-exceptions-manually-in-python
How to manually raising (throwing) an exception in Python? | Better Stack Community
January 26, 2023 - To manually raise an exception in Python, use the raise statement. Here is an example of how to use it: ... def calculate_payment(amount, payment_type): if payment_type != "Visa" and payment_type != "Mastercard": raise ValueError("Payment type ...
🌐
Real Python
realpython.com › python-raise-exception
Python's raise: Effectively Raising Exceptions in Your Code – Real Python
October 20, 2025 - If an exception of any type occurs, then you log the actual error using the logging module from the standard library and finally reraise the active exception using a bare raise statement.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-raise-keyword
Python Raise Keyword - GeeksforGeeks
May 12, 2026 - Traceback (most recent call last): File "c:\Users\gfg0753\practice 2.py", line 3, in <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.