2

I am trying to handle exceptions in Python 3.6. I want to handle every possible exception and print the exception. When i do

try:
    raise RuntimeError("Test")

except:
    e = sys.exc_info()[0]
    print(e)

it just prints

class '_mysql_exceptions.OperationalError'

How do i get the message of the Exception? In this case i would like the output to be "Test".

no0by5
  • 632
  • 3
  • 8
  • 30
  • Possible duplicate of [Python: about catching ANY exception](http://stackoverflow.com/questions/4990718/python-about-catching-any-exception) – daphtdazz Mar 09 '17 at 13:00

1 Answers1

11

You can catch and print the Exception as follows:

try:
    raise RuntimeError("Test")
except Exception as e:
    print(e)
    # Test

I'm not quite sure why you're trying to catch every Exception though, it would seem more prudent to let Python handle and raise these for you in general. Normally you would only catch specific Exceptions.

This behavior is not specific to Python 3.6.

Chris_Rands
  • 38,994
  • 14
  • 83
  • 119
  • I am connecting to a database and there can be many different Exceptions, so i don't want to handle every of these. But it's working, thank you – no0by5 Mar 09 '17 at 12:52
  • @no0by5 You should catch only the `Exception`s you expect to see and want to handle, e.g. `except RuntimeError` – Chris_Rands Mar 09 '17 at 12:53