0
class My_custom_exception(Exception):
    def __init__(self, ErrNum, *arg, **kwargs):
        self.ErrNum = int(ErrNum)
        self.ErrMsg = ""  # Set appropriate message depending an error number

        if self.ErrNum  & 0x00000000 !=0:
            self.ErrMsg = "NO ERROR"
        if self.ErrNum   & 0x00000001 !=0:
            self.ErrMsg  = "Error 1 occured"
        if self.ErrNum   & 0x00000002 !=0:
            self.ErrMsg  = "Error 2 occured"
        if self.ErrNum   & 0x00000004 !=0:
            self.ErrMsg  = "Error 3 occured"
        if self.ErrNum   & 0x00000008 !=0:
            self.ErrMsg  = "Error 4 occured"

   def __str__(self):
        return "ERROR (0x%08X): %s" % (self.ErrNum, self.ErrMsg )

    def __repr__(self):
        return self.__str__()


def check_error(error_nr):
    if error_nr > 0:
        raise My_custom_exception(error_nr)

try:
    check_error(3)
except My_custom_exception as e:
    print e

output:

My_custom_exception (0x00000003): Error 2 occurred.

My aim is to print both Error 1 occurred and Error 2 occurred.

Another problem if I give check_error(5) then Error 4 occurred, I want to avoid this as well.

2
  • @jonrsharpe, You mean self.ErrMsg should be dictionary, So that i can append each time? Commented Sep 9, 2015 at 10:08
  • I suppose you could do it like that, but you could use an ordered structure (I've shown a list below) or concatenate strings (i.e. add to self.ErrMsg rather than overwriting it). Commented Sep 9, 2015 at 10:10

2 Answers 2

2

I would do this as follows:

class MyCustomException(Exception):  # note naming convention

    MESSAGES = {
        0x00000000: 'NO ERROR',
        0x00000001: 'Error 1 occurred',
        0x00000002: 'Error 2 occurred',
        0x00000004: 'Error 3 occurred',
        ...
    }

    def __init__(self, err_num, *args, **kwargs):
        super(MyCustomException, self).__init__(*args, **kwargs)  # handle inheritance
        self.err_num = int(err_num)
        self.err_msg = self._create_err_msg(self.err_num)

    def __str__(self):
        return "ERROR (0x%08X): %s" % (self.err_num, self.err_msg)

    def __repr__(self):
        # Note that __repr__ should be eval-able
        return 'MyCustomException(%d)' % self.err_num

    @classmethod
    def _create_err_msg(cls, err_num):
        messages = []
        for num, msg in cls.MESSAGES.items():
            if err_num & num:
                messages.append(msg)
        return ' and '.join(messages) if messages else cls.MESSAGES[0]

Note that this simplifies the code, by extracting the error messages into a dictionary class attribute; making it a separate method also makes it easier to test in isolation:

>>> MyCustomException._create_err_msg(5)
'Error 1 occurred and Error 3 occurred'
>>> MyCustomException._create_err_msg(2)
'Error 2 occurred'
>>> MyCustomException._create_err_msg(0)
'NO ERROR'

In use:

>>> exc = MyCustomException(5)
>>> str(exc)
'ERROR (0x00000005): Error 1 occurred and Error 3 occurred'
Sign up to request clarification or add additional context in comments.

Comments

1

this may work: collect the errors in a list (the formatting may need some work but this should be a start):

class My_custom_exception(Exception):
    def __init__(self, ErrNum, *arg, **kwargs):
        self.ErrNum = int(ErrNum)
        self.ErrMsgs = []

        if self.ErrNum  & 0x00000000 !=0:
            self.ErrMsgs = ["NO ERROR"]
        if self.ErrNum   & 0x00000001 !=0:
            self.ErrMsgs.append("Error 1 occured (0x00000001)")
        if self.ErrNum   & 0x00000002 !=0:
            self.ErrMsgs.append("Error 2 occured (0x00000002)")
        if self.ErrNum   & 0x00000004 !=0:
            self.ErrMsgs.append("Error 3 occured (0x00000004)")
        if self.ErrNum   & 0x00000008 !=0:
            self.ErrMsgs.append("Error 4 occured (0x00000008)")

    def __str__(self):
        return "ERRORS: %s" % ', '.join(self.ErrMsgs)

the output for your example:

ERRORS: Error 1 occured (0x00000001), Error 2 occured (0x00000002)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.