How to catch an exception message in python?

Viewed 5187

I want something of the form

try:
  # code
except *, error_message:
  print(error_message)

i.e I want to have a generic except block that catches all types of exceptions and prints an error message. Eg. "ZeroDivisionError: division by zero". Is it possible in python?

If I do the following I can catch all exceptions, but I won't get the error message.

try:
  # code
except:
  print("Exception occurred")
2 Answers

Try this:

except Exception as e:
    print(str(e))

This will allow you to retrieve the message of any exception derived from the Exception base class:

try:
    raise Exception('An error has occurred.')
except Exception as ex:
    print(str(ex))
Related