Handling Exceptions in Python 3.6

no0by5 picture no0by5 · Mar 9, 2017 · Viewed 13.8k times · Source

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

Answer

Chris_Rands picture Chris_Rands · Mar 9, 2017

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.