python 自定义异常捕获

我们在处理程序异常的时候,可能需要自己定义一些传入的message,自己定义一些error对应的error_code,在后续做异常统计的时候可以有自定义的数据,这时候其实我们可以自定义异常捕获类。
异常类一般都是继承自Exception,自定义异常类如下:

class PangolinException(Exception):
    """
    Customized Exception for Pangolin Style Inspection Test
    Exception raised for errors in the input salary.
    Attributes:
        msg  -- error message
        code -- error attribution
    """

    msg, code = "", 0

    def __init__(self, **kwargs):
        for k, v in kwargs.items():
            setattr(self, k, v)


class UnknownException(PangolinException):
    code = 100


class ClickableItemClickFailedException(PangolinException):
    """
    clickable item clicking failed
    """

    msg = "failed to click item"
    code = 1


class ClickableItemNotFoundException(PangolinException):
    """
    clickable item not found
    """

    msg = "clickable item not found"
    code = 2


定义了异常类之后,可以在程序可能出现这些异常的时候,raise这些异常

 def random_click(self, item, items) -> ClickInfo:
      if len(items) == 0:
          raise ClickableItemClickFailedException()
      if not self.is_clickable(item):
          logger.info("item is not visible, retry")
          raise ClickableItemClickFailedException(msg="item is not visible")
      item_attr, item_rect = self.click_item(item)
      return ClickInfo(result=True, click_area=item_attr, x=item_rect.center[0], y=item_rect.center[1], error=[])

并在相应的时候去进行捕获

def click(self, item, items) -> ClickInfo:
	error_list = []
	try:
		result: ClickInfo = self.random_click(item, items)
	except Exception as e:
		# 此时捕获到的是具体的异常类实例
		error_list.append(e)
	for error in error_list:
		print("msg={}, code={}".format(error.msg, error.code))

如果之前raise的异常是ClickableItemNotFoundException,那将打印出

msg=item is not visible, code=2

如果raise的异常是ClickableItemClickFailedException,那将打印出

msg=failed to click item, code=1

版权声明:本文为Audreybiubiu原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。