Printing out actual error message for ValueError

Question:

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.

Asked By: wrongusername

||

Answers:

try:
    ...
except ValueError as e:
    print(e)
Answered By: snapshoe

Python 3 requires casting the exception to string before printing:

try:
    ...
except ValueError as error:
    print(str(error))
Answered By: Bengt

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

Answered By: Subham

Another way of accessing the message is via args:

try:
    ...
except ValueError as e:
    print(e.args[0])
Answered By: Paul P
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.