如何以pythonic方式禁用或启用自定义异常

时间:2015-10-01 06:36:16

标签: python exception-handling

from ctypes import *
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]

def some_function():
    error =0
    # do some operation then return if any error
    return error

 def test():
     disbaleexecption = 1   # I want to disable and enable exception in pythonic way, i need help here
     if not disbaleexecption:
         err = some_function()
         try:                                     # If any error occurs raise exception and catch the perticular exception and notice to the user,
                                                  # I want to do in more pythonic way, I need help on this
            raise MyCustomException(err)
         except MyCustomException as error:
            windll.user32.MessageBoxA(0, "My error", error, 6)
     else:
        err = some_function()                     # If disabled an exception , just print on the console , I want to do in pythonic way
        if err:
            print "error",err


    if __name__ == '__main__':
        test()

如何在Python中启用或禁用自定义例外并记录引发例外的行号?

1 个答案:

答案 0 :(得分:1)

为了启用/禁用您希望如何处理异常,通常在程序中使用调试“标志”,例如。

import sys, traceback  # Needed for pulling out your full stackframe info

debug = True
try:
    err = some_function()
except MyCustomException as error:
    if debug:
        # Print to the console
        print "error: ", error
        # To get the traceback information
        exc_type, exc_value, exc_traceback = sys.exc_info()
        print traceback.format_exc()
        # or
        print traceback.extract_tb(exc_traceback)
    else:
        windll.user32.MessageBoxA(0, "My error", error, 6)

您可以查看Traceback Documentation了解更多示例。