Use the as statement. You can read more about this in Handling Exceptions.

>>> try:
...     print(a)
... except NameError as e:
...     print(dir(e))  # print attributes of e
...
['__cause__', '__class__', '__context__', '__delattr__', '__dict__', '__doc__', '__eq__',
 '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__',
 '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
 '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__traceback__', 'args',
 'with_traceback']
Answer from Ashwini Chaudhary on Stack Overflow
🌐
Python
docs.python.org › 3 › library › exceptions.html
Built-in Exceptions — Python 3.14.4 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.
🌐
Programiz
programiz.com › python-programming › property
Python @property Decorator (With Examples)
# Making Getters and Setter methods class Celsius: def __init__(self, temperature=0): self.set_temperature(temperature) def to_fahrenheit(self): return (self.get_temperature() * 1.8) + 32 # getter method def get_temperature(self): return self._temperature # setter method def set_temperature(self, value): if value < -273.15: raise ValueError("Temperature below -273.15 is not possible.") self._temperature = value · As we can see, the above method introduces two new get_temperature() and set_temperature() methods. Furthermore, temperature was replaced with _temperature. An underscore _ at the beginning is used to denote private variables in Python.
🌐
W3Schools
w3schools.com › python › ref_exception_valueerror.asp
Python ValueError Exception
try: x = float("hello") except ValueError: print("The value has wrong format") except: print("Something else went wrong") Try it Yourself » ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com · HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
Top answer
1 of 6
209

I encountered another problem that returns the same error.

Single quote issue

I used a json string with single quotes :

{
    'property': 1
}

But json.loads accepts only double quotes for json properties :

{
    "property": 1
}

Final comma issue

json.loads doesn't accept a final comma:

{
  "property": "text", 
  "property2": "text2",
}

Solution: ast to solve single quote and final comma issues

You can use ast (part of standard library for both Python 2 and 3) for this processing. Here is an example :

import ast
# ast.literal_eval() return a dict object, we must use json.dumps to get JSON string
import json

# Single quote to double with ast.literal_eval()
json_data = "{'property': 'text'}"
json_data = ast.literal_eval(json_data)
print(json.dumps(json_data))
# Displays : {"property": "text"}

# ast.literal_eval() with double quotes
json_data = '{"property": "text"}'
json_data = ast.literal_eval(json_data)
print(json.dumps(json_data))
# Displays : {"property": "text"}

# ast.literal_eval() with final coma
json_data = "{'property': 'text', 'property2': 'text2',}"
json_data = ast.literal_eval(json_data)
print(json.dumps(json_data))
# Displays : {"property2": "text2", "property": "text"}

Using ast will prevent you from single quote and final comma issues by interpet the JSON like Python dictionnary (so you must follow the Python dictionnary syntax). It's a pretty good and safely alternative of eval() function for literal structures.

Python documentation warned us of using large/complex string :

Warning It is possible to crash the Python interpreter with a sufficiently large/complex string due to stack depth limitations in Python’s AST compiler.

json.dumps with single quotes

To use json.dumps with single quotes easily you can use this code:

import ast
import json

data = json.dumps(ast.literal_eval(json_data_single_quote))

ast documentation

ast Python 3 doc

ast Python 2 doc

Tool

If you frequently edit JSON, you may use CodeBeautify. It helps you to fix syntax error and minify/beautify JSON.

2 of 6
87

json.loads will load a json string into a python dict, json.dumps will dump a python dict to a json string, for example:

>>> json_string = '{"favorited": false, "contributors": null}'
'{"favorited": false, "contributors": null}'
>>> value = json.loads(json_string)
{u'favorited': False, u'contributors': None}
>>> json_dump = json.dumps(value)
'{"favorited": false, "contributors": null}'

So that line is incorrect since you are trying to load a python dict, and json.loads is expecting a valid json string which should have <type 'str'>.

So if you are trying to load the json, you should change what you are loading to look like the json_string above, or you should be dumping it. This is just my best guess from the given information. What is it that you are trying to accomplish?

Also you don't need to specify the u before your strings, as @Cld mentioned in the comments.

🌐
Real Python
realpython.com › python-property
Python's property(): Add Managed Attributes to Your Classes – Real Python
December 15, 2024 - class Point: def __init__(self, x, y): self.x = x self.y = y @property def x(self): return self._x @x.setter def x(self, value): try: self._x = float(value) print("Validated!") except ValueError: raise ValueError('"x" must be a number') from None @property def y(self): return self._y @y.setter def y(self, value): try: self._y = float(value) print("Validated!") except ValueError: raise ValueError('"y" must be a number') from None · The setter methods of .x and .y use try … except blocks that validate input data using the Python EAFP (easier to ask forgiveness than permission) style.
🌐
Python documentation
docs.python.org › 3 › tutorial › errors.html
8. Errors and Exceptions — Python 3.14.3 documentation
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
Find elsewhere
🌐
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.
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-valueerror-exception-handling-examples
Python ValueError Exception Handling: Examples & Fixes | DigitalOcean
August 3, 2022 - Python ValueError is raised when a function receives an argument of the correct type but an inappropriate value.
🌐
Python Module of the Week
pymotw.com › 2 › exceptions
exceptions – Built-in error classes - Python Module of the Week
A ValueError is used when a function receives a value that has the right type but an invalid value. ... $ python exceptions_ValueError.py Traceback (most recent call last): File "exceptions_ValueError.py", line 12, in <module> print chr(1024) ValueError: chr() arg not in range(256)
🌐
Readthedocs
portingguide.readthedocs.io › en › latest › exceptions.html
Exceptions — Conservative Python 3 Porting Guide 1.0 documentation
In Python 3, one single object includes all information about an exception: raise ValueError('invalid input') e = ValueError('invalid input') e.__traceback__ = some_traceback raise e
🌐
CodeRivers
coderivers.org › blog › python-value-error
Python ValueError: Understanding, Handling, and Best Practices - CodeRivers
April 18, 2025 - Here, the + operator is trying to add a list and a string, which are incompatible types, resulting in a TypeError. In contrast, a ValueError is about the value within the correct type being incorrect. Many built-in Python functions and methods can raise ValueError.
🌐
Turing
turing.com › kb › valueerror-in-python-and-how-to-fix
What is ValueError in Python & How to fix it
When a user calls a function with an invalid value but a valid argument, Python raises ValueError. Even though the value is the correct argument, it typically happens in mathematical processes that call for a specific kind of value.
🌐
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
🌐
Carleton University
cs.carleton.edu › cs_comps › 1213 › pylearn › final_results › encyclopedia › valueError.html
Error Encyclopedia | Value Error
>>> a, b, c, d = [3, 4, 5] Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: need more than 3 values to unpack · This returns a value error, because there are too few values on the right-hand side for Python to ‘unpack.’ When Python tries to assign ‘d’ to a value on the right-hand side, it is unable to find any matching value to ‘unpack’, and thus throws a ValueError.
🌐
Rollbar
rollbar.com › home › how to fix valueerror exceptions in python
How to Fix ValueError Exceptions in Python | Rollbar
June 24, 2024 - The person is a valid human, but their age is inappropriate for the setting. Similarly, a ValueError occurs when a function receives the correct type of input but with an unsuitable value. The Python ValueError is raised when an object is assigned the right data type but the wrong value for a certain operation.
Top answer
1 of 1
3

I think you misunderstand what ValueError (and in general, an Exception) is.

Exceptions are a way for a method to signal to its caller that some critical error condition has been encountered that would prevent that method from executing as intended. Python's try-except-finally control structure provides a way for the caller to detect those error conditions and react accordingly.

ValueError is a standard Exception raised by various methods that perform range-checking of some kind to signal that a value provided to the method fell outside the valid range. In other words, it's a universal way of signaling that error condition. ValueError by itself doesn't do any kind of checking. There are many other standard Exceptions like this; KeyError signifies that you tried to access a key in a mapping structure (like a dict or set) that didn't exist, IndexError means you tried to index into a list-like structure to an invalid location, etc. None of them actually do anything special in and of themselves, they're simply a way of directly specifying exactly what kind of problem was encountered by the called method.

Exceptions go hand in hand with the idiom in python that it is generally considered 'easier to ask forgiveness than permission'. Many languages support exceptions of course, but Python is one of the few where you will very frequently see code where the Exception case is actually a commonly-followed code path rather than one that only happens when something has gone really wrong.

Here is an example of the correct use of a ValueError:

def gen(selection):
    if imode == 0:
        # do EOS stuff here
    elif imode == 1:
        # do S2 stuff here
    else:
        raise ValueError("Please Select An Option Between 0-1")

def selector():
    while True:
        try:
            gen(int(input("Generate for EOS(0) or S2(1)")))
            break
        except ValueError as e: # This will actually satisfy two cases; If the user entered not a number, in which case int() raises, or if they entered a number out of bounds, in which chase gen() raises.
            print(e) 

Note there are probably much more direct ways to do what you want, but this is just serving as an example of how to correctly use a ValueError.

🌐
ZetCode
zetcode.com › python › property-builtin
Python property Function - Complete Guide
class Temperature: def __init__(self, celsius): self._celsius = celsius def get_celsius(self): return self._celsius def set_celsius(self, value): if value < -273.15: raise ValueError("Temperature below absolute zero") self._celsius = value celsius = property(get_celsius, set_celsius) temp = Temperature(25) print(temp.celsius) # 25 temp.celsius = 30 print(temp.celsius) # 30 try: temp.celsius = -300 # Raises ValueError except ValueError as e: print(e) This example shows property creation with separate getter and setter methods. The property ensures temperature values are physically valid while maintaining a clean interface. The _celsius naming convention indicates it's a protected attribute. Users interact with the celsius property instead of the attribute. Python's decorator syntax provides a cleaner way to define properties.