Search code examples
pythonexceptionprintingexcept

Python - How to print the message inside ValidationError


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


Solution

  • 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.