/ python

Python2 Exception args

Some inspects on Python2 Exception object.

  • Exception only accept positional arguments.
  • If only one argument passed to Exception, message attribute is that argument.
  • If more than one argument passed to Exception, message attribute is empty string.
  • You can get all your arguments via args attribute.

You'd better create your own exception and inherits from Exception, create __str__ and __unicode__ methods if you are using Python2, implements string format in __unicode__ and let __str__ call __unicode__, e.g.

class MyException(Exception):
    def __str__(self):
        return unicode(self).encode(encoding='UTF-8')
    def __unicode__(self):
        return u'my exception'