python自定义异常必须继承exception 对不对_python 自定义异常类的使用,继承Exception...

自定义异常类全部继承自BaseError

import traceback

class BaseError(Exception):

def __init__(self):

self.err_msg = ''

self.err_msg_detail = ''

class RequestParamsError(BaseError):

def __init__(self, err_msg):

self.err_msg = {'code': 70011, 'message': '请求参数错误'}

self.err_msg_detail = "请求参数错误" + err_msg

Exception.__init__(self, self.err_msg, self.err_msg_detail)

def try_test():

x = "yuihdjs"

try:

y = int(x)

except Exception as ep:

raise RequestParamsError(str(ep))

if __name__ == "__main__":

try:

try_test()

except BaseError as err: # 当抛出的异常是“自定义异常”时执行此语句

print(err.err_msg['message'])

print(err.err_msg_detail)

print(str(traceback.format_exc())) # 打印错误发生点

except Exception as ep:# 当抛出的异常是“非自定义异常”时执行此语句

print(str(ep))

print(str(traceback.format_exc()))

执行打印如下:

请求参数错误

请求参数错误invalid literal for int() with base 10: ‘yuihdjs’

Traceback (most recent call last):

File “D:/HtmlWorkSpace/my_test/module/webtest/test.py”, line 25, in try_test

y = int(x)

ValueError: invalid literal for int() with base 10: ‘yuihdjs’

During handling of the above exception, another exception occurred:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值