raise ValueError('could not find %c in %s' % (ch,str))

Answer from NPE on Stack Overflow
🌐
Python documentation
docs.python.org › 3 › tutorial › errors.html
8. Errors and Exceptions — Python 3.14.7 documentation
The most common pattern for handling Exception is to print or log the exception and then re-raise it (allowing a caller to handle the exception as well): import sys try: f = open('myfile.txt') s = f.readline() i = int(s.strip()) except OSError as err: print("OS error:", err) except ValueError: print("Could not convert data to an integer.") except Exception as err: print(f"Unexpected {err=}, {type(err)=}") raise
Top answer
1 of 4
191

raise ValueError('could not find %c in %s' % (ch,str))

2 of 4
30

Here's a revised version of your code which still works plus it illustrates how to raise a ValueError the way you want. By-the-way, I think find_last(), find_last_index(), or something simlar would be a more descriptive name for this function. Adding to the possible confusion is the fact that Python already has a container object method named __contains__() that does something a little different, membership-testing-wise.

def contains(char_string, char):
    largest_index = -1
    for i, ch in enumerate(char_string):
        if ch == char:
            largest_index = i
    if largest_index > -1:  # any found?
        return largest_index  # return index of last one
    else:
        raise ValueError('could not find {!r} in {!r}'.format(char, char_string))

print(contains('mississippi', 's'))  # -> 6
print(contains('bababa', 'k'))  # ->
Traceback (most recent call last):
  File "how-to-raise-a-valueerror.py", line 15, in <module>
    print(contains('bababa', 'k'))
  File "how-to-raise-a-valueerror.py", line 12, in contains
    raise ValueError('could not find {} in {}'.format(char, char_string))
ValueError: could not find 'k' in 'bababa'

Update — A substantially simpler way

Wow! Here's a much more concise version—essentially a one-liner—that is also likely faster because it reverses (via [::-1]) the string before doing a forward search through it for the first matching character and it does so using the fast built-in string index() method. With respect to your actual question, a nice little bonus convenience that comes with using index() is that it already raises a ValueError when the character substring isn't found, so nothing additional is required to make that happen.

Here it is along with a quick unit test:

def contains(char_string, char):
    #  Ending - 1 adjusts returned index to account for searching in reverse.
    return len(char_string) - char_string[::-1].index(char) - 1

print(contains('mississippi', 's'))  # -> 6
print(contains('bababa', 'k'))  # ->
Traceback (most recent call last):
  File "better-way-to-raise-a-valueerror.py", line 9, in <module>
    print(contains('bababa', 'k'))
  File "better-way-to-raise-a-valueerror", line 6, in contains
    return len(char_string) - char_string[::-1].index(char) - 1
ValueError: substring not found
Discussions

Raise ValueError - including variables in the error message
F-strings. raise ValueError(f"Parameter too high: {parameter}. The maximum parameter is 1.") f before the first quote, any variables in curly braces { } Works on any strings. Lots more things you can do with them. Definitely worth learning. More on reddit.com
🌐 r/learnpython
3
2
October 20, 2023
I need help on how to raise a value error
If it is, raise a ValueError. ... Try adjusting your code to match this logical sequence. ... Thing 1: I suggest reading this article about how to find the length of a string object in Python. More on teamtreehouse.com
🌐 teamtreehouse.com
1
February 10, 2024
Manually raising (throwing) an exception in Python - Stack Overflow
Valid in Python 2, but not in Python 3 is the following: raise ValueError, 'message' # Don't do this, it's deprecated! More on stackoverflow.com
🌐 stackoverflow.com
Python Basics: Raising Value Error
Python Development Techdegree Student 2,536 Points ... I've made a function that creates brand new product names using "artificial intelligence". I have a problem though, people keep on adding product ideas that are too short. It makes the suggestions look bad. Can you please raise a ValueError if ... More on teamtreehouse.com
🌐 teamtreehouse.com
3
March 9, 2021
🌐
Real Python
realpython.com › ref › builtin-exceptions › valueerror
ValueError | Python’s Built-in Exceptions – Real Python
ValueError is a built-in exception that gets raised when a function or operation receives an argument of the correct type, but its actual value isn’t acceptable for the operation at hand, and no more specific exception, such as IndexError, ...
🌐
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.

🌐
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.
🌐
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.
Find elsewhere
🌐
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.
🌐
Team Treehouse
teamtreehouse.com › community › i-need-help-on-how-to-raise-a-value-error
I need help on how to raise a value error (Example) | Treehouse Community
February 10, 2024 - Thing 3: Check out how to use if statements in Python. If the length of product_idea is less than 3, you want to raise a ValueError. But if this isn't the case, you want to return product_idea + "inator".
🌐
Python
docs.python.org › 3 › builtins › exceptions.html
Built-in Exceptions — Python 3.14.7 documentation
If an object is meant to support a given operation but has not yet provided an implementation, NotImplementedError is the proper exception to raise. 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.
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.

🌐
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
🌐
Inngest
inngest.com › blog › python-errors-as-values
Python errors as values: Comparing useful patterns from Go and Rust - Inngest Blog
November 8, 2023 - raise Exception(f"failed to update: {err}") from err · try: log_thing(thing) except Exception as err: # Swallow error because logging isn't critical · pass · return user · As we think about each possible error we realize that our original logic would crash the program when we didn't want it to! But while this is safe it's also extremely verbose. Python engineers overwhelmingly agree, which is why most Python code has 1 large try/catch at best: def upsert_thing(thing_id: str) -> Thing: try: thing = get_thing(thing_id) thing.set_name("Doodad") update_thing(thing) log_thing(thing) except Exception as err: raise Exception(f"something errored ¯\_(ツ)_/¯: {err}") return thing ·
🌐
Turing
turing.com › kb › valueerror-in-python-and-how-to-fix
What is ValueError in Python & How to fix it
This kind of mistake frequently occurs during mathematical calculations, when a ValueError Python arises. We will discuss the process to handle it in Python. When a user calls a function with an invalid value but a valid argument, Python raises ...
🌐
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.
🌐
Team Treehouse
teamtreehouse.com › community › python-basics-raising-value-error
Python Basics: Raising Value Error (Example) | Treehouse Community
March 9, 2021 - def suggest(product_idea): if len(product_idea) < 3: raise ValueError() return product_idea + "inator” · Hope that helps. Python Development Techdegree Student 2,536 Points
🌐
MangoHost
mangohost.net › mangohost blog › python valueerror – exception handling with examples
Python ValueError – Exception Handling With Examples
August 3, 2025 - class UserRegistrationValidator: """ Validates user registration data with proper ValueError handling """ @staticmethod def validate_age(age_input): try: age = int(age_input) if age < 13: raise ValueError("Age must be at least 13 years") if age > 120: raise ValueError("Age must be less than 120 years") return age except ValueError as ve: if "invalid literal" in str(ve): raise ValueError("Age must be a valid number") raise # Re-raise custom ValueError messages @staticmethod def validate_phone(phone_input): try: # Remove common formatting characters cleaned_phone = phone_input.replace("-", "").r
🌐
Python Morsels
pythonmorsels.com › how-to-throw-an-exception
How to raise an exception in Python - Python Morsels
January 17, 2022 - We're using Python's raise statement and passing in a TypeError exception object. We're using TypeError because the wrong type was given. Also, if the number given is less than 2, we'll say that this isn't a valid value, so we'll raise a ValueError exception.
🌐
APXML
apxml.com › courses › python-for-beginners › chapter-9-handling-errors-exceptions › python-raising-exceptions
Raising Python Exceptions | `raise` Statement
def calculate_rectangle_area(length, width): """Calculates the area of a rectangle.""" if length <= 0 or width <= 0: # Raise a ValueError if dimensions are non-positive raise ValueError("Rectangle dimensions 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 as e: print(f"Error calculating area: {e}") # Example with another invalid input try: area3 = calculate_rectangle_area(10, 0) # This will also raise an exception print(f"Area 3: {area3}") except ValueError as e: print(f"Error calculating area: {e}")
🌐
iO Flood
ioflood.com › blog › python-valueerror
[SOLVED] Python ValueError | Causes and Solutions
January 30, 2024 - It works fine when we pass ‘2021-10-30’. However, when we pass ’30-10-2021′, it raises a ValueError because the input does not match the expected format. Again, we use a try-except block to catch and handle this error. This way, even if a ValueError occurs, our program doesn’t crash and can continue to run other tasks. This example illustrates how ValueError can occur in more complex scenarios and how you can handle them effectively. Python offers several other techniques for handling errors, such as else and finally clauses in try-except blocks.
🌐
Manning
livebook.manning.com › wiki › categories › python › raise
python - raise wiki
The raise statement in Python is used to trigger exceptions. It can be employed to raise both built-in exceptions and custom exceptions defined by the user. The syntax of the raise statement allows for the inclusion of an exception type and an optional message, providing context about the error ...