CKTIS / Python
ValueError — an inappropriate argument value
ValueError indicates that an argument has the correct type but an unacceptable value. Learn how it differs from TypeError and how to raise and catch it.
Version: Python 3.14; repository image, production runtime not attested
Syntax
# Pattern 1: Raise ValueError
raise ValueError(message)
# Pattern 2 (separate snippet): Catch ValueError from an operation
try:
operation()
except ValueError as exc:
handle(exc)ValueError is a built-in exception raised when an operation receives an argument of the correct type but with an inappropriate value, and no more specific exception, such as IndexError, describes the situation. An inappropriate argument type is instead signaled by TypeError.
In your own code, use raise ValueError(message) to reject a value that violates a function's requirements. In the example, the number 120 is outside the permitted percentage range of 0 through 100, inclusive. The function checks the range; it is not comprehensive type validation.
Catch an expected error with except ValueError as exc. The variable exc refers to the exception object, which you can print to obtain its message. This clause also catches subclasses of ValueError. Keep the try block limited to the operation whose failure you intend to handle, rather than hiding unrelated failures with broad exception handling.
The example explicitly raises and handles the exception, so it prints the supplied message rather than an unhandled traceback. The expected output does not constitute confirmation that a test has been executed.
Examples
def validate_percentage(value):
if not 0 <= value <= 100:
raise ValueError("percentage must be between 0 and 100")
return value
try:
validate_percentage(120)
except ValueError as exc:
print(f"ValueError: {exc}")Result
ValueError: percentage must be between 0 and 100
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.