python 自定义异常类的使用,继承Exception
程序员文章站
2022-03-15 11:42:23
...
自定义异常类全部继承自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:
下一篇: 折半查找