天天看點

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: