Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

I want to know the best method to get the exception messages from elements of the standard library in Python.

I have used the below code:

try:

  pass

except Exception as ex:

  print(ex.message)

But in some cases like socket errors, I think we have to this:

try:

  pass

except socket.error as ex:

  print(ex)

1 Answer

0 votes
by (108k points)

Please be informed that most Exception classes in Python will have a message attribute as their first argument. 

The correct method to deal with this is to identify the specific Exception subclasses you want to catch and then catch only those instead of everything with an Exception, then use whatever parameters that specific subclass defines however you want.

Try the below code:

try:

    pass

except Exception as e:

    # Just print(e) is cleaner and more likely what you want,

    # but if you insist on printing message specifically whenever possible...

    if hasattr(e, 'message'):

        print(e.message)

    else:

        print(e)

Related questions

0 votes
1 answer
asked Nov 25, 2020 in Python by ashely (50.2k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...