简体   繁体   中英

Handling Exceptions in Python 3.6

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

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 Exception s.

This behavior is not specific to Python 3.6.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM