Fix Python – How to get exception message in Python properly


Asked By – FrozenHeart

What is the best way to get exceptions’ messages from components of standard library in Python?

I noticed that in some cases you can get it via message field like this:

except Exception as ex:

but in some cases (for example, in case of socket errors) you have to do something like this:

except socket.error as ex:

I wondered is there any standard way to cover most of these situations?

Now we will see solution for issue: How to get exception message in Python properly


If you look at the documentation for the built-in errors, you’ll see that most Exception classes assign their first argument as a message attribute. Not all of them do though.

Notably,EnvironmentError (with subclasses IOError and OSError) has a first argument of errno, second of strerror. There is no messagestrerror is roughly analogous to what would normally be a message.

More generally, subclasses of Exception can do whatever they want. They may or may not have a message attribute. Future built-in Exceptions may not have a message attribute. Any Exception subclass imported from third-party libraries or user code may not have a message attribute.

I think the proper way of handling this is to identify the specific Exception subclasses you want to catch, and then catch only those instead of everything with an except Exception, then utilize whatever attributes that specific subclass defines however you want.

If you must print something, I think that printing the caught Exception itself is most likely to do what you want, whether it has a message attribute or not.

You could also check for the message attribute if you wanted, like this, but I wouldn’t really suggest it as it just seems messy:

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'):

This question is answered By – ArtOfWarfare

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0