wrongusername
wrongusername

Reputation: 18918

Printing out actual error message for ValueError

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.

Upvotes: 69

Views: 99906

Answers (4)

Paul P
Paul P

Reputation: 3927

Another way of accessing the message is via args:

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

Upvotes: 13

Subham
Subham

Reputation: 411

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

Upvotes: 0

Bengt
Bengt

Reputation: 14488

Python 3 requires casting the exception to string before printing:

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

Upvotes: 8

snapshoe
snapshoe

Reputation: 14294

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

Upvotes: 102

Related Questions