5

I would like to know how to print the string written when raising an exception.

For example if I use

raise ValidationError("RANDOM TEXT HERE");

How can I retreive "RANDOM TEXT HERE" from within the except section.

try:
  ...
except ValidationError:
  ...
  // something like Java's ex.getMessage();
  .....

Thank you

Rorchackh
  • 2,113
  • 5
  • 22
  • 38

2 Answers2

8

If you bind the exception to a variable, then you could get its string representation with str(exception_variable).

Namely:

try:
  ...
except ValidationError as e:
  print str(e)

Edit: Changed msg to message

Second edit: Realized that exceptions are inconsistent between storing messages in msg vs message. str(exception) seems to be the most consistent.

Zach
  • 998
  • 1
  • 9
  • 26
1

I know this is old question, but I also faced same issue and I write my solution for anyone needs in future.

When I use e variable, it gave me a list, so I used e.message

try:
  ...
except ValidationError as e:
  print e.message
Ismayil Ibrahimov
  • 440
  • 1
  • 7
  • 11