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.
try:
...
except ValueError as e:
print(e)
print(str(e)).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.Python 3 requires casting the exception to string before printing:
try:
...
except ValueError as error:
print(str(error))
print(error) works just fine in that context in Python 3.print("Error: " + e) would fail if you do not cast the string. Using proper formatting: print(f"Error: {e}") works just fineAnother 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