7

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")
Eeshaan
  • 1,557
  • 1
  • 10
  • 22

2 Answers2

12

Try this:

except Exception as e:
    print(str(e))
Jakob
  • 1,858
  • 2
  • 15
  • 26
4

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))
Óscar López
  • 232,561
  • 37
  • 312
  • 386