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:
try: pass except Exception as ex: print(ex.message)
but in some cases (for example, in case of socket errors) you have to do something like this:
try: pass except socket.error as ex: print(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.
EnvironmentError (with subclasses
OSError) has a first argument of
errno, second of
strerror. There is no
strerror is roughly analogous to what would normally be a
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
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
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:
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)