Printing out actual error message for ValueError

PythonPython 3.xException

Python Problem Overview


How can I actually print out the ValueError's message after I catch it?

If I type except ValueError, err: into my code instead of except ValueError as err:, I get the error SyntaxError: invalid syntax.

Python Solutions


Solution 1 - Python

try:
    ...
except ValueError as e:
    print(e)

Solution 2 - Python

Python 3 requires casting the exception to string before printing:

try:
    ...
except ValueError as error:
    print(str(error))

Solution 3 - Python

Another approach using logging

import logging
try:
    int("dog")
except Exception as e:
    logging.warning(e)
    logging.error(e)

gives

WARNING:root:invalid literal for int() with base 10: 'dog'
ERROR:root:invalid literal for int() with base 10: 'dog'

[Program finished]

Just typing the exception gives,

invalid literal for int() with base 10: 'dog'

[Program finished]

Depends on how you want to process the output

Solution 4 - Python

Another way of accessing the message is via args:

try:
    ...
except ValueError as e:
    print(e.args[0])

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionwrongusernameView Question on Stackoverflow
Solution 1 - PythonsnapshoeView Answer on Stackoverflow
Solution 2 - PythonBengtView Answer on Stackoverflow
Solution 3 - PythonSubhamView Answer on Stackoverflow
Solution 4 - PythonPaul PView Answer on Stackoverflow