python 自定义异常捕获

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

class CustomException(Exception):
    """
    Customized Exception
    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(CustomException):
    code = 100


class ItemClickFailedException(CustomException):
    """
    clickable item clicking failed
    """

    msg = "failed to click item"
    code = 1


class ItemNotFoundException(CustomException):
    """
    clickable item not found
    """

    msg = "clickable item not found"
    code = 2


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

 def random_click(self, item, items) -> Info:
      if len(items) == 0:
          raise ItemClickFailedException()
      if not self.is_clickable(item):
          raise ItemClickFailedException(msg="item is not visible")
      item_attr, item_rect = self.click_item(item)
      return Info(result=True, 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的异常是ItemNotFoundException,那将打印出

msg=item is not visible, code=2

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

msg=failed to click item, code=1
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值