Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 468
no0by5 Avatar asked Nov 30 '25 14:11

no0by5


1 Answers

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.

like image 112
Chris_Rands Avatar answered Dec 02 '25 03:12

Chris_Rands



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!