69

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.

0

4 Answers 4

103
try:
    ...
except ValueError as e:
    print(e)
Sign up to request clarification or add additional context in comments.

6 Comments

Note that in Python 3 you have to cast to string explicitly: print(str(e)).
It's not true that you have to cast to string explicitly in Python 3. At least as of 3.5.
Note that in Python 3 you have to cast to string explicitly: print(str(e)), at least for Python 3.6.6
@Bengt I think you should post it as an answer. Python 3.7.5 requires the cast
I concur with @snapshoe, it isn't true, that the exception object has to be casted to a string before printing; you have this in the print function documentation: "All non-keyword arguments are converted to strings like str() does". I can only assume, so please bear with me, but you might have done a concatenation like print('Error is: ' + str(e)) when the cast is indeed required, but that is because of the concatenation and not the print function.
|
14

Another way of accessing the message is via args:

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

Comments

8

Python 3 requires casting the exception to string before printing:

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

3 Comments

This is still not true. print(error) works just fine in that context in Python 3.
@snapshoe If this is not true, why does it get upvoted? Perhaps there are cases where it is really needed? I doubt it, but who knows
@questionto42 using previous concating of strings causes this to be needed : ie: print("Error: " + e) would fail if you do not cast the string. Using proper formatting: print(f"Error: {e}") works just fine
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.